每行输入一个简单的算术表达式,如输入表达式:3*(7-2)
using namespace std;
//stack<int>OPND;//运算栈
//stack<char>OPTR;//操作符栈
char per(char t1,char t2) // 判断两个运算符的优先级
{
char f;
switch(t2)
{
case '+':
case '-': if(t1=='('||t1=='#')
f='<';
else
f='>';
break;
case '*':
case '/':if(t1=='*'||t1=='/'||t1==')')
f='>';
else
f='<';
break;
case '(': if(t1==')')
{
break;
}
else
f='<';
break;
case ')':switch(t1)
{
case '(':f='=';
break;
case '#':break;
default: f='>';
}
break;
case '#':switch(t1)
{
case '#':f='=';
break;
case '(':break;
default: f='>';
}
}
return f;
}
int operate(int a,char ch,int b){
if(ch=='-'){
return b-a;
}else if(ch=='+'){
return a+b;
}else if(ch=='*'){
int m=a*b;
return m;
}else{
int m=b/a;
return m;
}
}
int main(){
char ch;
string h,p="#";
int m;
int now;
while(cin>>h){
// }
h=h+p;int i=0;
stack<int>OPND;
stack<char>OPTR;
OPTR.push('#');
ch=h[i++];
now=0;
while(ch!='#'||OPTR.top()!='#'){
if(ch>='0'&&ch<='9'){
now=now*10;
now=now+ch-'0';
ch=h[i++];
}else{
if(now!=0)
OPND.push(now);
now=0;
switch(per(OPTR.top(),ch))
{
case '=':OPTR.pop();ch=h[i++];break;//抵消//
case '<':OPTR.push(ch);ch=h[i++];break;//大于//
case '>':char theta=OPTR.top();OPTR.pop();
int a=OPND.top();OPND.pop();int c=OPND.top();OPND.pop();
m=operate(a,theta,c);
OPND.push(m);break;//小于//
}
}
}
m=OPND.top();OPND.pop();
if(m==1){
m=19;
}
//printf("%d",m);
cout<<m<<'\n';
}
return 0;
}