主要思路:
遇到数字就入栈,遇到运算符号就把栈中的两个数字弹出,计算出结果之后将结果压入栈中。
代码:
#include<iostream>
#include<cstring>
#include<cctype>
#include<cstdlib>
using namespace std;
typedef struct STRACK{
double a[100];
int top;
} STRACK;
double Cal(double a,double b,int e)//根据e的值决定进行什么运算
{
double ans;
if(e==1)
ans=a+b;
if(e==2)
ans=a-b;
if(e==3)
ans=a*b;
if(e==4)
ans=a*1.0/b;
return ans;
}
void Calculate(char *s)
{
int len=strlen(s);
double ans=0;
STRACK L;
memset(L.a,0,sizeof(L.a));
L.top=-1;
for(int i=0;i<len;i++){//遇到数字入栈
if(isdigit(s[i])){
L.top++;
L.a[L.top]=s[i]-'0';
}else{//遇到运算符进行计算
double e=0;
switch(s[i])
{
case '+': e=Cal(L.a[L.top-1],L.a[L.top],1);break;
case '-': e=Cal(L.a[L.top-1],L.a[L.top],2);break;
case '*': e=Cal(L.a[L.top-1],L.a[L.top],3);break;
case '/': e=Cal(L.a[L.top-1],L.a[L.top],4);break;
}
L.a[L.top-1]=e;//记得往前一位存储
L.a[L.top]=0;
L.top--;
}
}
ans=L.a[0];//到最后,栈里应该只有一个数字,直接输出也可以
cout<<ans<<endl;
}
int main()
{
char str[100]; //str里储存后缀表达式
while(cin>>str)
{
Calculate(str);
}
}
关于中缀怎么变后缀在前一篇文章里。