如果给的是前缀,算最后的结果,则要先转化为后缀
#include<iostream>
#include<stack>
#include<string>
using namespace std;
int main() {
string str;
stack<int> s;
cin >> str;
for (int i = 0; i < str.length(); i++) {
if (str[i] >= '0'&&str[i] <= '9')
s.push(str[i]-'0');
else if (str[i] == '+'||str[i]=='-') {
int a = s.top();
s.pop();
int b = s.top();
s.pop();
if (str[i] == '+') {
int sum=b+a;
s.push(sum); //注意这里的逻辑
}
else {
int sum = b - a;
s.push(sum);
}
}
}
cout << s.top(); //注意这里的逻辑
system("pause");
return 0;
}