#include<iostream>
#include<string>
#include<stack>
#include<cstdio>
using namespace std;
int op(int a, int b, char ch)
{
if (ch == '+') return b + a; //注意运算顺序
if (ch == '-') return b - a;
if (ch == '*') return b * a;
if (ch == '/') return b / a;
}
//后缀表达式求值‘0’——‘9’是48-57
int main()
{
string str;
cin >> str;
stack<char> vc;
int ret;
for (int i = 0; i < str.size(); i++)
{
if (str[i] >= 48 && str[i] <= 57)//是数字
{
vc.push(str[i]);
}
else
{
int tempa = vc.top() - '0'; vc.pop();
int tempb = vc.top() - '0'; vc.pop();
ret = op(tempa, tempb, str[i]);
vc.push(ret+'0');
}
}
cout << vc.top() - '0' << endl;
return 0;
}
输入:123*+42/-(即是中缀表达式的1+2*3-4/2)
输出:5
网友评论