利用栈来计算表达式的值

利用栈来计算表达式的值

#include <iostream>
#include <stack>
using namespace std;

int getPriority(char op){
    if(op=='*'||op=='/'){
        return 2;
    }else if(op=='+'||op=='-'){
        return 1;
    }
}

float cal01(float od1,char op,float od2){
    switch(op){
        case '+':return od1+od2;
        case '-':return od1-od2;
        case '*':return od1*od2;
        case '/':return od1/od2;
    }
}

float cal(string s){
    stack <int> od;
    stack <char> op;
    float tn=0,od1,od2,result=0;
    char op1;
    int lastpriority=0,priority;
    for(int i=0;i<s.size();i++){
        if((s[i]>='0')&&(s[i]<='9')){
            tn=tn*10+float(s[i]-'0');
        }else if(s[i]==' '){
        }else{
            od.push(tn);
            priority=getPriority(s[i]);
            if(lastpriority>=priority){
                while(!op.empty()){
                    op1=op.top();
                    lastpriority=getPriority(op1);
                    if(lastpriority>=priority){
                        op.pop();
                        od2=od.top();
                        od.pop();
                        od1=od.top();
                        od.pop();
                        od1=cal01(od1,op1,od2);
                        od.push(od1);
                    }else{
                        break; //避免死循环 
                    }
                }
                op.push(s[i]);
            }else{ //优先级高于上一个 
                op.push(s[i]);
            }
            tn=0;
            lastpriority=priority;
        }
    }
    //把最后一个操作数加上
    od.push(tn);
    while(!op.empty()){
        op1=op.top();
        op.pop();
        od2=od.top();
        od.pop();
        od1=od.top();
        od.pop();
        result=cal01(od1,op1,od2);
        od.push(result);
    } 
    return result; 
}

int main(){
    cout<<"12+2*3+4/2-1="<<cal("12+2*3+4/2-1")<<endl;
    return 0;
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值