输入中缀表达式的字符串,可能存在括号,输出计算结果。
除法是向0取整,仅包含加减乘除四则运算。
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
stack<char> op; //存运算符
stack<int> num; //存运算数
unordered_map<char, int> pr={{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}}; //定义优先级
void eval() //计算最后两个数
{
int b = num.top();
num.pop();
int a = num.top();
num.pop();
char c = op.top();
op.pop();
int x;
if (c == '*') x = a * b;
else if (c == '/') x = a / b;
else if (c == '+') x = a + b;
else x = a - b;
num.push(x);
}
int main()
{
string s;
cin >> s;
for (int i = 0; i < s.size(); i ++ )
{
char c = s[i];
if (isdigit(c)) //将数压入栈
{
int x = 0;
int j = i;
while (j < s.size() && isdigit(s[j]))
{
x = x * 10 + s[j] - '0';
j ++ ;
}
num.push(x);
i = j - 1;
}
else if (c == '(') op.push(c);
else if (c == ')')
{
while (op.top() != '(') eval();
op.pop();
}
else
{
//当前一个运算符优先级较高时进行计算
while (op.size() && pr[op.top()] >= pr[c]) eval();
op.push(c);
}
}
while (op.size()) eval(); //可能还没算完
cout << num.top(); //计算结果是栈顶元素
return 0;
}