假定算数表达式的值均为非负整数常数,不包含变量、小 数和字符常量。 试设计一个算术四则运算表达式求值的简单计算器。 基本要求: 1、 操作数均为非负整数常数,操作符仅为+、-、*、/、(、); 2、 编写 main 函数进行测试
时间: 2023-11-08 16:05:40 浏览: 39
好的,我明白了。这是一个关于算术四则运算表达式求值的问题。
可以通过逆波兰表达式来实现计算器的功能。具体步骤如下:
1. 将中缀表达式转换为后缀表达式(也就是逆波兰表达式),并将其存储在栈中。
2. 遍历后缀表达式,如果是操作符,则从栈中取出两个操作数进行计算,并将计算结果重新压入栈中。
3. 最终,栈中只剩下一个值,即为计算结果。
下面是代码实现:
```
#include <iostream>
#include <stack>
#include <string>
#include <cstdlib>
using namespace std;
// 判断是否为操作符
bool isOperator(char c) {
return c == '+' || c == '-' || c == '*' || c == '/';
}
// 判断操作符优先级
int operatorPriority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
}
return 0;
}
int main() {
stack<int> stk; // 存储操作数
string exp; // 中缀表达式
cin >> exp;
string postExp; // 后缀表达式
for (int i = 0; i < exp.size(); i++) {
char c = exp[i];
if (isdigit(c)) { // 操作数
int num = c - '0';
while (i + 1 < exp.size() && isdigit(exp[i + 1])) {
num = num * 10 + exp[++i] - '0';
}
postExp += to_string(num);
postExp += ' ';
} else if (c == '(') { // 左括号
stk.push(c);
} else if (c == ')') { // 右括号
while (!stk.empty() && stk.top() != '(') {
postExp += stk.top();
postExp += ' ';
stk.pop();
}
stk.pop();
} else if (isOperator(c)) { // 操作符
while (!stk.empty() && stk.top() != '(' && operatorPriority(c) <= operatorPriority(stk.top())) {
postExp += stk.top();
postExp += ' ';
stk.pop();
}
stk.push(c);
}
}
while (!stk.empty()) {
postExp += stk.top();
postExp += ' ';
stk.pop();
}
cout << "后缀表达式: " << postExp << endl;
// 遍历后缀表达式计算结果
stack<int> stk2;
for (int i = 0; i < postExp.size(); i++) {
char c = postExp[i];
if (isdigit(c)) { // 操作数
int num = c - '0';
while (i + 1 < postExp.size() && isdigit(postExp[i + 1])) {
num = num * 10 + postExp[++i] - '0';
}
stk2.push(num);
} else if (isOperator(c)) { // 操作符
int b = stk2.top();
stk2.pop();
int a = stk2.top();
stk2.pop();
int res = 0;
if (c == '+') {
res = a + b;
} else if (c == '-') {
res = a - b;
} else if (c == '*') {
res = a * b;
} else if (c == '/') {
res = a / b;
}
stk2.push(res);
}
}
cout << "计算结果: " << stk2.top() << endl;
return 0;
}
```
该程序的基本思路就是将中缀表达式转换为后缀表达式,再遍历后缀表达式求值。