假定算数表达式的值均为非负整数常数,不包含变量、小 数和字符常量。 试设计一个算术四则运算表达式求值的简单计算器。 基本要求: 1、 操作数均为非负整数常数,操作符仅为+、-、*、/、(、); 2、 编写 main 函数进行测试
时间: 2023-11-08 09:09:44 浏览: 45
好的,我明白了。关于你的问题,我可以给出以下简单计算器的解决方案:
```
#include <iostream>
#include <stack>
#include <vector>
#include <cmath>
using namespace std;
// 定义运算符的优先级
int getPriority(char op) {
if (op == '(') return 1;
if (op == '+' || op == '-') return 2;
if (op == '*' || op == '/') return 3;
return 0; // 非法字符返回 0
}
// 计算结果
int calculate(int a, int b, char op) {
if (op == '+') return a + b;
if (op == '-') return a - b;
if (op == '*') return a * b;
if (op == '/') return a / b;
return 0; // 非法字符返回 0
}
// 对表达式求值并返回结果
int evaluate(string expression) {
stack<int> operandStack;
stack<char> operatorStack;
vector<char> validOperators = {'+', '-', '*', '/', '(', ')'};
for (int i = 0; i < expression.length(); i++) {
char c = expression[i];
if (c == ' ') continue;
if (isdigit(c)) {
int j = i;
int operand = 0;
while (j < expression.length() && isdigit(expression[j])) {
operand = 10 * operand + (expression[j] - '0');
j++;
}
i = j - 1;
operandStack.push(operand);
} else if (find(validOperators.begin(), validOperators.end(), c) != validOperators.end()) {
if (operatorStack.empty() || c == '(' || (getPriority(c) > getPriority(operatorStack.top()))) {
operatorStack.push(c);
} else {
while (!operatorStack.empty() && getPriority(c) <= getPriority(operatorStack.top())) {
char op = operatorStack.top();
operatorStack.pop();
if (op == '(') break;
int b = operandStack.top();
operandStack.pop();
int a = operandStack.top();
operandStack.pop();
operandStack.push(calculate(a, b, op));
}
if (c != ')') {
operatorStack.push(c);
}
}
}
}
while (!operatorStack.empty()) {
char op = operatorStack.top();
operatorStack.pop();
int b = operandStack.top();
operandStack.pop();
int a = operandStack.top();
operandStack.pop();
operandStack.push(calculate(a, b, op));
}
return operandStack.top();
}
int main() {
string expression = "3+2*(7-2)/3";
int result = evaluate(expression);
cout << result << endl;
return 0;
}
```
这个程序可以解释字符串表示的算术表达式,例如 "3+2*(7-2)/3",并返回其结果。我希望这可以帮助您完成您的计算器编程任务。
注意,这段代码的主要特点是堆栈的使用。我们用一个操作数堆栈来存储数字,用一个运算符堆栈来存储运算符。当我们遇到一个数字时,将其推入操作数堆栈;当我们遇到一个运算符时,我们比较它与堆栈上面的运算符的优先级,然后选择将其推入堆栈或从堆栈中推出操作数和运算符。最终,我们将操作数和运算符完全弹出堆栈并进行计算。
这个方法在处理算术表达式方面非常有效,因为它可以处理括号和优先级等复杂的情况。当然,您也可以使用其他数据结构和算法来编写这样一个计算器,这只是其中的一种可行方案。