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 中国大陆许可协议进行许可。

posted @   MoonOut  阅读(33)  评论(0编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  1. 1 Sibelius: Violin Concerto in D Minor, Op. 47:III. Allegro, ma non tanto Jascha Heifetz / Chicago Symphony Orchestra
Sibelius: Violin Concerto in D Minor, Op. 47:III. Allegro, ma non tanto - Jascha Heifetz / Chicago Symphony Orchestra
00:00 / 00:00
An audio error has occurred.