中缀表达式求值
2026-03-21 20:36:39
发布于:北京
#include<bits/stdc++.h>
using namespace std;
stack<int> num;
stack<char> op;
int getPriority(char op) {
if (op == '+' || op == '-')
return 0; //+或-的优先级比较低
return 1;
}
void calc() {
int r = num.top();
num.pop();//栈顶是右操作数
int l = num.top();
num.pop();//次栈顶是左操作数
if (op.top() == '+') num.push(l + r);
if (op.top() == '-') num.push(l - r);
if (op.top() == '/') num.push(l / r);
if (op.top() == '*') num.push(l * r);
op.pop();//弹出运算符
}
int main() {
string s;
cin >> s;
for (int i = 0; i < s.length(); i++) {
if (s[i] >= '0' && s[i] <= '9') {
num.push(s[i] - '0');
} else {
if (s[i] == '(') {
op.push(s[i]);//左括号直接进栈
} else if (s[i] == '+' || s[i] == '-' || s[i] == '*' || s[i] == '/') {
while (op.size() && op.top() != '(' && getPriority(op.top()) >= getPriority(s[i])) {
calc();
}
op.push(s[i]);
} else if (s[i] == ')') {
while (op.top() != '(') {
calc();
}
op.pop();//弹出左括号
}
}
}
while (op.size()) {
calc();
}
cout << num.top();
return 0;
}
这里空空如也


















有帮助,赞一个