题目:ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。
比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数)
思路:这是关于栈的应用,采用的是后缀表达式。关于“( )”的处理 ,“(”是拥有最高的优先级,因此会被放进栈中,除非正在处理“)”否则“(”是不会弹出的。当读到“)”,将栈中的元素直到“)”弹出。运算符的优先级处理,当操作符栈的栈顶元素比读到的元素的优先级低的话,不会输出且该元素进栈,如果比读到元素的优先级高的话,栈顶元素弹出,然后将读到的元素压入栈中。(AC通过)
#include <iostream>
#include <string>
#include <stack>
#include <fstream>
using namespace std;
bool isAS(char c){
return (c=='+' || c=='-');
}
bool isMD(char c){
return (c=='*' || c=='/');
}
string transform(string m){
stack<char> s;
string str;
int i;
char w;
for(i=0;i<m.size();i++){
if(m[i]=='='){
break;
}
if(isdigit(m[i]) || m[i]=='.'){
while(isdigit(m[i]) || m[i]=='.') str += m[i++];
i--;
str += '$';
}
else if(isAS(m[i])){
while(s.size() && (isAS(s.top()) || isMD(s.top()))){
str+=s.top();
s.pop();
}
s.push(m[i]);
}
else if(m[i]==')'){
while(s.top()!='('){
str+=s.top();
s.pop();
}
s.pop();
}
else if(isMD(m[i])){
while(s.size() && isMD(s.top())){
str+=s.top();
s.pop();
}
s.push(m[i]);
}
else s.push(m[i]);
}
while(s.size()){
str+=s.top();
s.pop();
}
return str;
}
double multen(int n){
double res=1;
for(int i=0;i<n;i++){
res *= 10;
}
return res;
}
double strDouble(string s){
double res=0;
char c;
int dec=0;
for(int i=1;i<=s.size();i++){
c=s[i-1];
if(c=='.') dec=i;
else if(!dec) res = res*10 + c-'0';
else res += (c-'0')/multen(i-dec);
}
return res;
}
double calculate(string s){
double res, t;
stack<double> num;
string temp;
int i;
for(i=0;i<s.size();i++){
temp="";
if(isdigit(s[i]) || s[i]=='.'){
while(isdigit(s[i]) || s[i]=='.') temp+=s[i++];
num.push(strDouble(temp));
}
else{
switch (s[i]){
case '+':
t=num.top();
num.pop();
t+=num.top();
num.pop();
num.push(t);
break;
case '-':
t=num.top();
num.pop();
t=num.top()-t;
num.pop();
num.push(t);
break;
case '*':
t=num.top();
num.pop();
t*=num.top();
num.pop();
num.push(t);
break;
case '/':
t=num.top();
num.pop();
t=num.top()/t;
num.pop();
num.push(t);
break;
}
}
}
res=num.top();
return res;
}
int main(){
int t;
string str, postfix;
cin>>t;
while(t--){
cin>>str;
postfix = transform(str);
cout.precision(2);
cout<<fixed;
cout<<calculate(postfix)<<endl;
//printf("%0.2f",calculate(postfix));
}
return 0;
}