表達式求值
時間限制:
3000 ms | 內存限制:65535 KB
難度:
4
- 描述
-
ACM隊的mdd想做一個計算器,但是,他要做的不僅僅是一計算一個A+B的計算器,他想實現隨便輸入一個表達式都能求出它的值的計算器,現在請你幫助他來實現這個計算器吧。 比如輸入:“1+2/4=”,程序就輸出1.50(結果保留兩位小數)
- 輸入
- 第一行輸入一個整數n,共有n組測試數據(n<10)。 每組測試數據只有一行,是一個長度不超過1000的字符串,表示這個運算式,每個運算式都是以“=”結束。這個表達式里只包含+-*/與小括號這幾種符號。其中小括號可以嵌套使用。數據保證輸入的操作數中不會出現負數。 數據保證除數不會為0
- 輸出
- 每組都輸出該組運算式的運算結果,輸出結果保留兩位小數。
- 樣例輸入
-
2 1.000+2/4= ((1+2)*5+1)/4=
- 樣例輸出
-
1.50 4.00
題解:
求后綴表達式,用后綴表達式,求解;
AC代碼:#include<cstdio> #include<iostream> #include<cmath> #include<algorithm> #include<cstring> #include<queue> #include<stack> using namespace std; const int INF=0x3f3f3f3f; #define mem(x,y) memset(x,y,sizeof(x)) #define SI(x) scanf("%d",&x) #define PI(x) printf("%d",x) typedef long long LL; const int MAXN=1010; char s[MAXN]; char work(char a,char b){ if(a=='#')return '<'; if(a=='+'||a=='-'){ if(b=='*'||b=='/'||b=='(')return '<'; else return '>'; } if(a=='*'||a=='/'){ if(b=='(')return '<'; else return '>'; } if(a=='('||a=='=') { if( (a=='('&&b==')')||(a=='='&&b=='=') ) return '='; else return '<'; } } int main(){ int T; SI(T); while(T--){ double temp,p,a,b; scanf("%s",s); stack<char>S; stack<double>s2; S.push('#'); for(int i=0;s[i];){ // printf("%c\n",s[i]); if(isdigit(s[i])||s[i]=='.'){ temp=0,p=10; while(isdigit(s[i])||s[i]=='.'){ if(s[i]=='.'){ p=0.1; i++; continue; } if(p==10)temp=temp*p+s[i]-'0'; else temp=temp+(s[i]-'0')*p,p*=0.1; i++; } // printf("%lf\n",temp); s2.push(temp); } //s2.push(s[i++]); else{ switch(work(S.top(),s[i])){ case '<': S.push(s[i]); i++; break; case '>': a=s2.top(); s2.pop(); b=s2.top(); s2.pop(); if(S.top()=='+') s2.push(a+b); else if(S.top()=='-') s2.push(b-a); else if(S.top()=='*') s2.push(a*b); else s2.push(b/a); //printf("%lf\n",s2.top()); S.pop(); break; case '=': S.pop(); i++; break; } } } //printf("%d %d %lf\n",S.size(),s2.size(),s2.top()); printf("%.2lf\n",s2.top()); } return 0; }