devc++用中缀表达式求值
时间: 2023-11-24 19:52:15 浏览: 80
以下是使用栈实现中缀表达式求值的示例代码:
```c++
#include <iostream>
#include <stack>
#include <string>
#include <cctype>
using namespace std;
// 定义操作符的优先级
int priority(char op) {
if (op == '+' || op == '-') {
return 1;
} else if (op == '*' || op == '/') {
return 2;
} else {
return 0;
}
}
// 计算两个数的结果
int calculate(int num1, int num2, char op) {
if (op == '+') {
return num1 + num2;
} else if (op == '-') {
return num1 - num2;
} else if (op == '*') {
return num1 * num2;
} else {
return num1 / num2;
}
}
// 中缀表达式求值
int evaluate(string expression) {
stack<int> numStack; // 存放操作数的栈
stack<char> opStack; // 存放操作符的栈
for (int i = 0; i < expression.length(); i++) {
char ch = expression[i];
if (isdigit(ch)) { // 如果是数字,将其转换为整数并压入操作数栈
int num = ch - '0';
while (i + 1 < expression.length() && isdigit(expression[i + 1])) {
num = num * 10 + (expression[i + 1] - '0');
i++;
}
numStack.push(num);
} else if (ch == '(') { // 如果是左括号,将其压入操作符栈
opStack.push(ch);
} else if (ch == ')') { // 如果是右括号,弹出操作符栈中的操作符并计算,直到遇到左括号
while (opStack.top() != '(') {
char op = opStack.top();
opStack.pop();
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
numStack.push(calculate(num1, num2, op));
}
opStack.pop(); // 弹出左括号
} else if (ch == '+' || ch == '-' || ch == '*' || ch == '/') { // 如果是操作符
while (!opStack.empty() && opStack.top() != '(' && priority(opStack.top()) >= priority(ch)) {
char op = opStack.top();
opStack.pop();
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
numStack.push(calculate(num1, num2, op));
}
opStack.push(ch);
}
}
while (!opStack.empty()) { // 处理剩余的操作符
char op = opStack.top();
opStack.pop();
int num2 = numStack.top();
numStack.pop();
int num1 = numStack.top();
numStack.pop();
numStack.push(calculate(num1, num2, op));
}
return numStack.top(); // 返回最终结果
}
int main() {
string expression = "3+4*5-(6+7)*8/9";
int result = evaluate(expression);
cout << "The result of " << expression << " is " << result << endl;
return 0;
}
```
阅读全文