#include<iostream>//中缀表达式求值
#include<stack>
using namespace std;
int precede(char t1,char t2) //shuru//判断优先级
{
int t=0;
switch(t2)
{
case '+':
case '-':
if(t1=='('||t1=='#') t=-1;
else t=1;
break;
case '*':
case '/':
if(t1=='*'||t1=='/'||t1==')')
t=1;
else t=-1;
break;
case '#':
if(t1=='#') t=0;
else t=1;
break;
case '(':
t=-1;
break;
case ')':
if(t1=='(') t=0;
else t=1;
break;
}
return t;
}
int operate(int m,char cp,int n)//就算
{
switch(cp)
{
case '+':
return m+n;
case '-':
return m-n;
case '*':
return m*n;
case '/':
return m/n;
}
return 0;
}
int main()
{
int m,n;
char cp;
stack<int> open;
stack<char> optr;
optr.push('#');//初始化
char input[]="3*(4+2)/2-5#";
int i=0;
while(input[i]!='\0')
{
if(input[i]>='0'&&input[i]<='9')
open.push(input[i]-'0');
else
switch(precede(optr.top(),input[i]))
{
case 1:
while(precede(optr.top(),input[i])==1)
{
m=open.top();
open.pop();
n=open.top();
open.pop();
cp=optr.top();
optr.pop();
open.push(operate(n,cp,m));
}
if(precede(optr.top(),input[i])==-1)
optr.push(input[i]);
else optr.pop();
break;
case -1:
optr.push(input[i]);
break;
case 0:
optr.pop();
break;
}
i++;
}
cout<<open.top()<<endl;
return 0;
}
#include<stack>
using namespace std;
int precede(char t1,char t2) //shuru//判断优先级
{
int t=0;
switch(t2)
{
case '+':
case '-':
if(t1=='('||t1=='#') t=-1;
else t=1;
break;
case '*':
case '/':
if(t1=='*'||t1=='/'||t1==')')
t=1;
else t=-1;
break;
case '#':
if(t1=='#') t=0;
else t=1;
break;
case '(':
t=-1;
break;
case ')':
if(t1=='(') t=0;
else t=1;
break;
}
return t;
}
int operate(int m,char cp,int n)//就算
{
switch(cp)
{
case '+':
return m+n;
case '-':
return m-n;
case '*':
return m*n;
case '/':
return m/n;
}
return 0;
}
int main()
{
int m,n;
char cp;
stack<int> open;
stack<char> optr;
optr.push('#');//初始化
char input[]="3*(4+2)/2-5#";
int i=0;
while(input[i]!='\0')
{
if(input[i]>='0'&&input[i]<='9')
open.push(input[i]-'0');
else
switch(precede(optr.top(),input[i]))
{
case 1:
while(precede(optr.top(),input[i])==1)
{
m=open.top();
open.pop();
n=open.top();
open.pop();
cp=optr.top();
optr.pop();
open.push(operate(n,cp,m));
}
if(precede(optr.top(),input[i])==-1)
optr.push(input[i]);
else optr.pop();
break;
case -1:
optr.push(input[i]);
break;
case 0:
optr.pop();
break;
}
i++;
}
cout<<open.top()<<endl;
return 0;
}