zoukankan      html  css  js  c++  java
  • 实验7:Problem D: 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容易实现。


    Append Code

    #include<iostream>
    #include<cstdio>
    #include<stack>
    #include<algorithm>
    using namespace std;
    int main() {
        int i,n;
        double a;
        char f;
        while(cin>>n) {
            stack<double>s;
            stack<char>t;
            while(n--){
                cin>>a>>f;
                if(!t.empty()) {
                    if(t.top()=='-')
                        a=-a;
                    else if(t.top()=='*') {
                        a*=s.top();
                        s.pop();
                    }
                    else if(t.top()=='/') {
                        a/=s.top();
                        s.pop();
                    }
                }
                s.push(a);
                t.push(f);
            }
            double sum=0;
            while(!s.empty()) {
                sum+=s.top();
    //            cout<<s.top()<<endl;
                s.pop();
            }
            printf("%.2lf
    ",sum);
        }
        return 0;
    }
    向代码最深处出发~!
  • 相关阅读:
    MySQL(后篇)
    数据库
    Ajax
    JQuery
    BOM & DOM
    CSS
    HTML
    Python之IO多路复用学习
    vue-router小记
    js中运算符的优先级
  • 原文地址:https://www.cnblogs.com/auto1945837845/p/5408899.html
Copyright © 2011-2022 走看看