这个题目可能有些问题,“直到两个堆栈都为空时,计算结束”,如果top1 || top2 会出现段错误
实际上题目下如果所有计算都是合法的,最后一定是sta中剩余一个数,就是最终的结果,staa为空。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 1010;
int n;
int sta[N], top1;
char staa[N];
int top2;//细节:不能和staa在一行定义
int main(){
cin >> n;
for(int i = 1; i <= n; i ++ ){
cin >> sta[i];
}
top1 = n;
getchar();//细节
string s;
getline(cin, s);
for(int i = 0; i < s.size(); i ++ ){
if(s[i] != ' ') staa[++ top2] = s[i];
}
// char c;
// while(cin >> c){ //两种写法皆可
// if(c != ' ') staa[++ top2] = c;
// }
int temp;
while(top1 && top2){
int n1 = sta[top1 -- ], n2 = sta[top1 -- ]; //两个后置++运算可以用在一行定义变量(/擦边)
char op = staa[top2 -- ];
if(op == '+') temp = n1 + n2;
else if(op == '-') temp = n2 - n1;
else if(op == '*') temp = n2 * n1;
else{
if(!n1){
cout << "ERROR: " << n2 << "/0" << endl;
return 0;
}
else temp = n2 / n1;
}
sta[++ top1] = temp;
}
cout << temp << endl;
return 0;
}