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 中国大陆许可协议进行许可。
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步