以下是使用 C++ 实现基于栈的中缀算术表达式求值的代码: ```cpp #include <iostream> #include <stack> #include <string> #include <cctype> double calculate(double num1, double num2, char op) { switch (op) { case '+': return num1 + num2; case '-': return num1 - num2; case '*': return num1 * num2; case '/': if (num2!= 0) { return num1 / num2; } else { std::cout << "除数不能为 0" << std::endl; return 0; } } return 0; } double evaluateInfixExpression(std::string expression) { std::stack<double> operandStack; std::stack<char> operatorStack; for (int i = 0; i < expression.size(); i++) { if (isdigit(expression[i]) || expression[i] == '.') { std::string numStr; while (i < expression.size() && (isdigit(expression[i]) || expression[i] == '.')) { numStr += expression[i++]; } i--; operandStack.push(atof(numStr.c_str())); } else if (expression[i] == '(') { operatorStack.push(expression[i]); } else if (expression[i] == ')') { while (operatorStack.top()!= '(') { double num2 = operandStack.top(); operandStack.pop(); double num1 = operandStack.top(); operandStack.pop(); char op = operatorStack.top(); operatorStack.pop(); operandStack.push(calculate(num1, num2, op)); } operatorStack.pop(); } else if (expression[i] == '+' || expression[i] == '-') { while (!operatorStack.empty() && operatorStack.top()!= '(') { double num2 = operandStack.top(); operandStack.pop(); double num1 = operandStack.top(); operandStack.pop(); char op = operatorStack.top(); operatorStack.pop(); operandStack.push(calculate(num1, num2, op)); } operatorStack.push(expression[i]); } else if (expression[i] == '*' || expression[i] == '/') { while (!operatorStack.empty() && (operatorStack.top() == '*' || operatorStack.top() == '/')) { double num2 = operandStack.top(); operandStack.pop(); double num1 = operandStack.top(); operandStack.pop(); char op = operatorStack.top(); operatorStack.pop(); operandStack.push(calculate(num1, num2, op)); } operatorStack.push(expression[i]); } } while (!operatorStack.empty()) { double num2 = operandStack.top(); operandStack.pop(); double num1 = operandStack.top(); operandStack.pop(); char op = operatorStack.top(); operatorStack.pop(); operandStack.push(calculate(num1, num2, op)); } return operandStack.top(); } int main() { std::string expression; while (true) { std::getline(std::cin, expression); if (expression == "=") { break; } double result = evaluateInfixExpression(expression.substr(0, expression.size() - 1)); std::printf("%.2f\n", result); } return 0; } ``` 这段代码实现了对中缀表达式的求值,通过两个栈分别存储操作数和操作符,并按照运算符的优先级进行计算。 [2024-10-26 20:10:49 | AI写代码神器 | 872点数解答]