//--------------------------------------【程序说明】-------------------------------------------//开发测试所用操作系统: 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.";}成功图片如下:
新闻热点
疑难解答