#include<iostream>
#include<cstdio>
#include<cstring>
#include<string>
using namespace std;
char a[256];
int stack[100];
char b[100];
int top1=0,top2=0,len,i=0,on=0,ans=0;
int chan(char x)
{
if(x=='-'||x=='+')
return 1;
else if(x=='*'||x=='/')
return 2;
else if(x=='(')
return 0;
}
void work()
{
if(b[top2-1]=='*')stack[top1-1]=stack[top1-1]*stack[top1];
if(b[top2-1]=='/')stack[top1-1]=stack[top1-1]/stack[top1];
if(b[top2-1]=='+')stack[top1-1]=stack[top1-1]+stack[top1];
if(b[top2-1]=='-')stack[top1-1]=stack[top1-1]-stack[top1];
top1--;
b[top2-1]=b[top2];
top2--;
}
int main()
{
gets(a);
len=strlen(a);
for(i=0;i<=len-1;i++)
{ if('0'<=a[i]&&a[i]<='9')
{
ans=ans*10+a[i]-'0';on=1;
}
else
{
if(on==1)
{
stack[++top1]=ans;
on=0;
ans=0;
}
if(a[i]=='(')
b[++top2]='(';
if(a[i]==')')
{
b[++top2]=')';
while(b[top2-1]!='(')
work();
top2-=2;
}
if(a[i]=='+'||a[i]=='-'||a[i]=='*'||a[i]=='/')
{
b[++top2]=a[i];
if(chan(b[top2])<=chan(b[top2-1]))
work();
}
}
}
top2++;
while(top2!=1)
work();
cout<<stack[top1]<<endl;
return 0;
}
中缀表达式
最新推荐文章于 2023-10-08 22:31:51 发布