后缀表达式计算的代码实现

主要思路:

遇到数字就入栈,遇到运算符号就把栈中的两个数字弹出,计算出结果之后将结果压入栈中。

代码:

#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);
    }
}

关于中缀怎么变后缀在前一篇文章里。

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值