把运算的处理专门放在一个函数里,然后通过优先级的判断去调用函数,注意那个’('还是放在else if里面吧,不要和运算混在一起了
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+10;
stack<int> s1;
stack<char> s2;
int flag=0;
//处理+-*/四个
map<char,int> cmp={
{'+',1}, {'-',1} , {'*',2}, {'/',2}
};
void eval(){
int b=s1.top();s1.pop();
int a=s1.top();s1.pop();
char c=s2.top();s2.pop();
int x;
if(c=='+') x=a+b;
if(c=='-') x=a-b;
if(c=='*') x=a*b;
if(c=='/'){
if(b==0) flag=1;
else x=a/b;
}
if(flag) s1.push(0);//随意进一个数
else s1.push(x);
}
int main(){
char a[N];
cin>>a;
int len=strlen(a);
for(int i=0;i<len;i++){
//数字
int n=0,isnum=0;
while(i<len && isdigit(a[i])){
n=n*10+a[i]-'0';
i++;
isnum=1;
}
if(isnum){
i--;
s1.push(n);
}
else if(a[i]=='(') s2.push(a[i]);
else if(a[i]==')'){
while(s2.size()&&s2.top()!='(') eval();
s2.pop();
}
else{//
while(s2.size()&&cmp[s2.top()]>=cmp[a[i]]) eval();
s2.push(a[i]);
}
}
//清理低优先级
while(s2.size()) eval();
if(flag) cout<<"ILLEGAL"<<endl;
else cout<<s1.top()<<endl;
return 0;
}
如果除数是0 的话,直接return 0 吧