STL——表达式求值

Description

给出一个表达式,求出其值。表达式中只存在 +、-、*、三种运算,我们假设表达式是正确的,

且不存在除数为零的情况。

 

Input

第一行输入一个正整数 n(1<=n<=30) ,表示有表达式 n 个数(每个数均小于100),表达式中只有数值(都是大于零的数)

 和运算符(包括+、-、*、=四种运算符,其中 = 只在表达式最后,表示一个表达式输出结束,且整个表达式不存在空格)

 

Output

表达式的值(表达式的值不会超出 double 的范围并保留两位小数)

 

Sample Input

5

1*2*3*4*5=

5

5-1-2+3+4=

Sample Output

120.00

9.00

HINT

 

使用STL的stack容易实现。

 

#include <bits/stdc++.h>
#include <stack>
#include <string>
#include<vector>
#include<algorithm>
#include<set>
using namespace std;

int main()
{
    int n;
    double x;
    char c;
    while(cin >> n)
    {
        double sum=0;
        stack<double> a;
        stack<char> b;
        for(int i=0;i<n;i++)
        {
            cin>>x>>c;
            if(!a.empty())
            {
                if(b.top()=='-')
                    x=-x;
                else if(b.top()=='*')
                {
                    x=a.top()*x;
                    a.pop();
                }
            }
            a.push(x);
            b.push(c);
            //cout << a.top() << endl;
        }
        while(!a.empty())
        {
            sum=sum+a.top();
            a.pop();
        }
        printf("%.2lf\n",sum);
    }
    return 0;
}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值