表达式求值

1792: 算法3-4:表达式求值

时间限制: 1 Sec  内存限制: 32 MB
提交: 34  解决: 22
[提交][状态][讨论版]

题目描述

算数四则运算的规则是1)先乘除,后加减;2)从左算到右;3)先括号内,后括号外。

由此,算式4+2*3-10/5的计算顺序为4+2*3-10/5=4+6-10/5=4+6-2=8。

给定一个以“#”作为结束符的算式,求出算式的结果。

输入

以“#”结尾的表达式,运算数为正整数。每个表达式占一行。

输出

输出表达式运算的结果。

样例输入

4+2*3-10/5#
3*(7-2)#
2*3/2#

样例输出

8
15
3

提示

提示:

使用栈来解决本题,很多人都会想到。但怎样建栈,却带来了问题。同样,严书上的代码实际上也给大家带来了问题。看过严书光盘中代码的人应该知道,代码中使用了两个栈,一个是存储运算符的,类型为char;另一个存储运算数,类型为float。而操作两个栈的函数都一样。要知道,除非像C++中使用泛型,C语言中却基本不能实现这样的操作。所以在C语言环境中需要将这两个栈结合在一起。由于char与int有种特别的联系,可以使用int来代替char存储运算符。

总结:

注意灵活运用栈,要是能够学习C++使用template就更好了。可以模拟STL了。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define rep(i,n) for(int i=0;i<(n);i++)
#define reps(i,f,n) for(int i=(f);i<(n);i++)
const int maxn=1e5+5;
stack<int>num;
stack<char>ch;
int cmp(char c)
{
    if(c=='+'||c=='-')
        return 1;
    else if(c=='*'||c=='/')
        return 2;
    else if(c=='('||c==')')
        return 0;
    return -1;
}
int js(int x,int y,char c)
{
    if(c=='+')
        return y+x;
    else if(c=='-')
        return y-x;
    else if(c=='*')
        return y*x;
    else
        return y/x;
}
void handle(char c)
{
    while(!ch.empty()&&cmp(ch.top())>=cmp(c))
    {
        int x=num.top();
        num.pop();
        int y=num.top();
        num.pop();
        num.push(js(x,y,ch.top()));
        ch.pop();
    }
}
int main()
{
    string s;
    int n,m;
    while(cin>>s)
    {
        n=s.size();
        m=0;
        rep(i,n)
        {
            if(s[i]>='0'&&s[i]<='9')
                m=m*10+(s[i]-'0');
            else
            {
                if(m>0)
                    num.push(m),m=0;
                if(s[i]=='#')
                {
                    handle(s[i]);
                    break;
                }
                if(s[i]=='(')
                    ch.push(s[i]);
                else if(s[i]==')')
                {
                    while(!ch.empty()&&ch.top()!='(')
                    {
                        int x=num.top();
                        num.pop();
                        int y=num.top();
                        num.pop();
                        num.push(js(x,y,ch.top()));
                        ch.pop();
                    }
                    ch.pop();
                }
                else
                {
                    if(ch.empty()||cmp(ch.top())<cmp(s[i]))
                        ch.push(s[i]);
                    else
                    {
                        handle(s[i]);
                        ch.push(s[i]);
                    }
                }
            }
        }
        printf("%d\n",num.top());
        num.pop();
    }
}

 

  • 5
    点赞
  • 21
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值