输入样例
#号为表达式结尾
2
1+2*3-4/5#
(66+(((11+22)*2-33)/3+6)*2)-45.6789#
输出样例
保留4位小数
6.2000
54.3211
answer
#include<iostream>
#include<iomanip>
#include<stack>
#include<map>
#include<cstdlib>
#include<string>
using namespace std;
map<char,int>m = {
{'(', 0},
{'+', 1},
{'-', 1},
{'*', 2},
{'/', 2},
};
double calculate(double n1, double n2, char ch){
if(ch=='+')return n1+n2;
else if(ch=='-')return n1-n2;
else if(ch=='*')return n1*n2;
else if(ch=='/')return n1/n2;
}
void calculate_process(stack<double>& num_stk, stack<char>&ch_stk){
double n2=num_stk.top();
num_stk.pop();
double n1=num_stk.top();
num_stk.pop();
char ch=ch_stk.top();
ch_stk.pop();
double num = calculate(n1, n2, ch);
num_stk.push(num);
}
int main(){
int n;
cin>>n;
for(int i=0; i<n; i++){
string s;
cin>>s;
stack<double>num_stk;
stack<char>ch_stk;
for(int j=0; j<s.size()-1; j++){
if(s[j] >= '0' && s[j] <= '9'){
int c=j;
while((s[c] >= '0' && s[c] <= '9')||s[c]=='.'){
c++;
}
c=c-j;
num_stk.push(atof(s.substr(j,c).c_str()));
j+=(c-1);
}
else if(ch_stk.empty() || s[j]=='(' || m[s[j]]>m[ch_stk.top()]){
ch_stk.push(s[j]);
}
else if(s[j]==')'){
while(ch_stk.top()!='('){
calculate_process(num_stk, ch_stk);
}
ch_stk.pop();
}
else{
while(!ch_stk.empty()&&m[s[j]]<=m[ch_stk.top()]){
calculate_process(num_stk, ch_stk);
}
ch_stk.push(s[j]);
}
}
while(!ch_stk.empty()){
calculate_process(num_stk, ch_stk);
}
cout<<fixed<<setprecision(4)<<num_stk.top()<<endl;
}
return 0;
}