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 一边算数,一边化表达式 */
本文作者:MoonOut
本文链接:https://www.cnblogs.com/moonout/p/16455624.html
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步