四则运算表达式求值

表达式求值是关于栈的应用,涉及到中缀与后缀式的转换,本文关于10以内不带括号的四则运算。

9 + 3 + 4 x 3 = 24
1 x 9 - 5 / 9 = 9
5 x 9 - 4 + 6 - 2 x 3 + 1 = 42   

思路:遇到数字直接入数字栈。遇到运算符,第一个运算符直接入符号栈,后面的需要与符号栈栈顶元素比较优先级。若当前优先级大于符号栈顶优先级(乘除大于加减),则直接入栈,否则先取栈内符号运算,至符号栈为空,再将当前符号入栈。

#include<bits/stdc++.h>
#define maxsize 500
using namespace std;

stack<int> num;
stack<char> op;
map<char,int> mp={{'+',-1},{'-',-1},{'x',1},{'/',1}};

void deal(char *s)
{
    int len = strlen(s);
    int n1,n2;
    while(!num.empty())
        num.pop();

    for(int i = 0;i < len; ++i){

        if(s[i] >= '0' && s [i] <= '9')
            num.push(s[i]-'0');
        else{

            if(op.empty())///第一个运算符处理
                op.push(s[i]);
            else{

                if(mp[s[i]] > mp[op.top()])///当前运算符优先级大于栈顶
                    op.push(s[i]);
                else{

                    while(!op.empty()){

                    n1 = num.top(),num.pop();
                    n2 = num.top(),num.pop();
                    if(op.top() == '+')
                        num.push(n1+n2);
                    if(op.top() == '-')
                        num.push(n2-n1);
                    if(op.top() == 'x')
                        num.push(n1*n2);
                    if(op.top() == '/')
                        num.push(n2/n1);
                    op.pop();

                    }

                    op.push(s[i]);
                }
            }
        }

    }
    while(!op.empty()){///处理剩余元素

        n1 = num.top(),num.pop();
        n2 = num.top(),num.pop();
        if(op.top() == '+')
            num.push(n1+n2);
        if(op.top() == '-')
            num.push(n2-n1);
        if(op.top() == 'x')
            num.push(n1*n2);
        if(op.top() == '/')
            num.push(n2/n1);
        op.pop();

    }

    printf("%d\n",num.top());
}
int main()
{
    char s[maxsize];
    while(~scanf("%s",&s))
        deal(s);
    return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值