//--------------------------------------【程序说明】------------------------------------------- //开发测试所用操作系统: 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' 包括' \ 0 int 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 复制不\ 0 if (*(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 term break; case '-': // - found so subtract ——发现减去 value -= term(str, index); // the next term break; 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 除以下一个数字 else break; } 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 character throw message; } while (isdigit(*(str + index))) // Loop accumulating leading digits 循环累积领先的数字 value = 10 * value + (*(str + index++) - '0'); // Not a digit when we get to here if (*(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 返回字符串在新的记忆 } else numL--; // Reduce count of '(' to be matched 减少“(”匹配的计数 break; case '(': numL++; // Increase count of '(' to be 增加的“(” // matched break; } } while (*(str + index++) != '\0'); // Loop - don't overrun end of string 循环——不要泛滥字符串的结束 throw "Ran off the end of the expression, must be bad input."; }
成功图片如下:
