2019北航夏令营机试 T2 后缀表达式计算

题意(请看第二题):

经验:

  • getline 读入单个换行符 / 读入带空格的字符串。
  • printf(d, "%.2lf")
  • cout.setf(ios::fixed); 保留 x 位小数时,补零补够 x 位。
  • cout<<expe.top().first<<"="<<setprecision(2)<<calc.top()<<endl; 保留两位小数。

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9+7;

stack<double> calc;
stack<pair<string, char>> expe;

int main(){
    ios::sync_with_stdio(false);
    string s; while(cin>>s){
        if(s=="#"){
            cout.setf(ios::fixed);
            cout<<expe.top().first<<"="<<setprecision(2)<<calc.top()<<endl;
            break;
        }
        else if(isdigit(s[0])){
            double d = stoi(s);
            calc.push(d); expe.push(pair<string, char>(
                to_string(int(d)), '*'));
        }
        else{
            double d2 = calc.top(); calc.pop(); double d1 = calc.top();
            pair<string, char> s2 = expe.top(); expe.pop();
            pair<string, char> s1 = expe.top();
            if(s=="+")
                calc.push(d1+d2), expe.push(pair<string, char>(
                    (s1.first+"+"+s2.first), '+'));
            else if(s=="-")
                calc.push(d1-d2), expe.push(pair<string, char>(
                    (s1.first+"-"+s2.first), '-'));
            else if(s=="*"){
                calc.push(d1*d2);
                if(s1.second=='+' || s1.second=='-') s1.first = "(" + s1.first + ")";
                if(s2.second=='+' || s2.second=='-') s2.first = "(" + s2.first + ")";
                expe.push(pair<string, char>(s1.first+"*"+s2.first, '*'));
            }
            else if(s=="/"){
                calc.push(d1/d2);
                if(s1.second=='+' || s1.second=='-') s1.first = "(" + s1.first + ")";
                if(s2.second=='+' || s2.second=='-') s2.first = "(" + s2.first + ")";
                expe.push(pair<string, char>(s1.first+"/"+s2.first, '/'));
            }
        }
    }
}


/*
3 2 - 4 + 22 * #
((3-2)+4)*22=110.00

一边算数,一边化表达式

*/

posted @ 2022-07-07 17:56  MoonOut  阅读(47)  评论(0)    收藏  举报