//--------------------------------------【程序說明】-------------------------------------------//開發測試所用操作系統: Windows 7 32bit//開發測試所用IDE版本:Visual Studio 2015
// A PRogram to implement a calculator accepting parentheses 一個程序實現一個計算器接受括號
#include <iostream> // For stream input/output 輸入/輸出流#include <cstdlib> // For the exit() function 退出()函數#include <cctype> // For the isdigit() function isdigit()函數#include <cstring> // For the strcpy() function strcpy()函數using std::cin;using std::cout;using std::cerr;using std::endl;void eatspaces(char* str); // Function to eliminate blanks 函數來消除空格double expr(char* str); // Function evaluating an expression 函數計算一個表達式double term(char* str, int& index); // Function analyzing a term 函數分析一個詞double number(char* str, int& index); // Function to recognize a number 函數來識別一個數字char* extract(char* str, int& index); // Function to extract a substring 函數來提取子字符串const int MAX(80); // Maximum expression length, 最大表達長度 // including '/0' 包括' / 0int main(){char buffer[MAX] = { 0 }; // Input area for expression to be evaluated 輸入表達式計算cout << endl<< "Welcome to your friendly calculator."<< endl<< "Enter an expression, or an empty line to quit."<< endl;for (;;){cin.getline(buffer, sizeof buffer); // Read an input line 讀取一個輸入行eatspaces(buffer); // Remove blanks from input 從輸入刪除空格if (!buffer[0]) // Empty line ends calculator 空行結束計算器return 0;try{cout << "/t= " << expr(buffer) // Output value of expression 輸出值的表達式<< endl << endl;}catch (const char* pEx){cerr << pEx << endl;cerr << "Ending program." << endl;return 1;}}}// Function to eliminate spaces from a string 從一個字符串函數來消除空間void eatspaces(char* str){int i(0); // 'Copy to' index to string “復制到”索引的字符串int j(0); // 'Copy from' index to string “臨摹”索引的字符串while ((*(str + i) = *(str + j++)) != '/0') // Loop while character 循環而性格// copied is not /0 復制不/ 0if (*(str + i) != ' ') // Increment i as long as 只要增量i++; // character is not a space 不是一個空間return;}// Function to evaluate an arithmetic expression 函數來評估一個算術表達式double expr(char* str){double value(0.0); // Store result here 這里存儲結果int index(0); // Keeps track of current character position 跟蹤當前的字符位置value = term(str, index); // Get first term 得到第一個任期 for (;;) // Indefinite loop, all exits inside 無限循環,所有出口{switch (*(str + index++)) // Choose action based on current character 基于當前的角色選擇行動{case '/0': // We're at the end of the string 我們在結束的字符串return value; // so return what we have got 所以我們必須返回case '+': // + found so add in the +發現添加的value += term(str, index); // next termbreak; case '-': // - found so subtract ——發現減去value -= term(str, index); // the next termbreak;default: // If we reach here the string 如果我們到達這里的字符串char message[38] = "Expression evaluation error. Found: "; //表達式求值的錯誤。發現:strncat_s(message, str + index - 1, 1); // Append the character 添加角色throw message;break;}}}// Function to get the value of a term 功能詞的價值double term(char* str, int& index){double value(0.0); // Somewhere to accumulate 積累的地方 // the result value = number(str, index); // Get the first number in the term 得到第一個數字// Loop as long as we have a good Operator 循環,只要我們有一個優秀的經營者while (true){if (*(str + index) == '*') // If it's multiply, 如果是用,value *= number(str, ++index); // multiply by next number 乘下一個數字else if (*(str + index) == '/') // If it's divide, 如果它是分裂, value /= number(str, ++index); // divide by next number 除以下一個數字elsebreak;}return value; // We've finished, so return what 我們已經完成了,所以返回什么// we've got 我們有}// Function to recognize a number in a string 函數來識別一個數字字符串double number(char* str, int& index){double value(0.0); // Store the resulting value 將得到的值存儲到if (*(str + index) == '(') // Start of parentheses 括號開始{char* psubstr(nullptr); // Pointer for substring 子串的指針psubstr = extract(str, ++index); // Extract substring in brackets 提取子字符串在括號中value = expr(psubstr); // Get the value of the substring 子字符串的值delete[]psubstr; // Clean up the free store 清理免費存儲return value; // Return substring value 返回字符串值}// There must be at least one digit...if (!isdigit(*(str + index))){ // There's no digits so input is junk... 沒有數字的輸入是垃圾……char message[31] = "Invalid character in number: "; //無效的字符的數量:strncat_s(message, str + index, 1); // Append the characterthrow message;}while (isdigit(*(str + index))) // Loop accumulating leading digits 循環累積領先的數字value = 10 * value + (*(str + index++) - '0');// Not a digit when we get to hereif (*(str + index) != '.') // so check for decimal point 所以檢查小數點return value; // and if not, return value 如果沒有,返回值double factor(1.0); // Factor for decimal places 小數點后因素while (isdigit(*(str + (++index)))) // Loop as long as we have digits 循環只要我們有數字{factor *= 0.1; // Decrease factor by factor of 10 減少因素的10倍value = value + (*(str + index) - '0')*factor; // Add decimal place 增加小數位}return value; // On loop exit we are done 在循環退出做完了}// Function to extract a substring between parentheses 括號之間的函數來提取子字符串// (requires cstring)char* extract(char* str, int& index){char* pstr(nullptr); // Pointer to new string for return 指針指向新的字符串返回int numL(0); // Count of left parentheses found 計算左括號的發現int bufindex(index); // Save starting value for index 保存起始值指數do{switch (*(str + index)){case ')':if (0 == numL){++index;pstr = new char[index - bufindex];if (!pstr){throw "Memory allocation failed.";}strncpy_s(pstr, index - bufindex, str + bufindex, index - bufindex - 1); // Copy substring to new memory 子串復制到新的記憶return pstr; // Return substring in new memory 返回字符串在新的記憶}elsenumL--; // Reduce count of '(' to be matched 減少“(”匹配的計數break;case '(':numL++; // Increase count of '(' to be 增加的“(” // matchedbreak;}} while (*(str + index++) != '/0'); // Loop - don't overrun end of string 循環——不要泛濫字符串的結束throw "Ran off the end of the expression, must be bad input.";}成功圖片如下:
新聞熱點
疑難解答