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();
}

浙公网安备 33010602011771号