2019北航夏令营机试 T2 复杂计算器

题意:

  • 用字符串代表变量,先给出一行中缀表达式,然后按变量出现的顺序,给出变量值。
  • 中缀表达式转后缀,要求输出后缀表达式,且输出运算结果。

输入输出用例:

(ab+cd+de)/(ab+cd)#
5 5 5
1.5

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9+7;
string expr;
stack<double> sym;
stack<char> ope;
map<string, double> value;
stack<string> postfix;
int main(){
ios::sync_with_stdio(false);
getline(cin, expr);
expr.erase(remove_if(expr.begin(), expr.end(),
[](unsigned char x){return isspace(x);}), expr.end());
int p = 0;
while(p<expr.length()){
if(isalpha(expr[p])){
int q = p+1; while(q<expr.length() && isalpha(expr[q])) ++q;
string sy = expr.substr(p, q-p); p=q;
cout<<"new symbol: "<<sy<<endl;
if(value.count(sy)==0){
double temp; cin>>temp; value[sy] = temp;
}
postfix.push(sy);
sym.push(value[sy]);
}
else if(expr[p]=='(') ope.push(expr[p]), ++p;
else{
while(
((expr[p]==')') && (ope.top()!='(')) ||
((expr[p]=='+'||expr[p]=='-'||expr[p]=='#') && (!ope.empty())&&ope.top()!='(') ||
((expr[p]=='*'||expr[p]=='/') && (!ope.empty())&&(ope.top()!='+')&&(ope.top()!='-'))
){
char operat = ope.top(); ope.pop();
cout<<"operat = "<<operat<<endl;
double d2 = sym.top(); sym.pop(); double d1 = sym.top(); sym.pop();
string s2 = postfix.top(); postfix.pop();
string s1 = postfix.top(); postfix.pop();
if(operat=='+')
postfix.push(s1+s2+"+"), sym.push(d1+d2);
else if(operat=='-')
postfix.push(s1+s2+"-"), sym.push(d1-d2);
else if(operat=='*')
postfix.push(s1+s2+"*"), sym.push(d1*d2);
else if(operat=='/')
postfix.push(s1+s2+"/"), sym.push(d1/d2);
cout<<postfix.top()<<" "<<sym.top()<<endl;
}
ope.push(expr[p]); ++p;
if(ope.top()==')') ope.pop(), ope.pop();
}
}
cout<<postfix.top()<<" = "<<setprecision(2)<<sym.top();
}

本文作者:MoonOut

本文链接:https://www.cnblogs.com/moonout/p/16456422.html

版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。

posted @   MoonOut  阅读(41)  评论(1编辑  收藏  举报
点击右上角即可分享
微信分享提示
评论
收藏
关注
推荐
深色
回顶
收起
  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.