郁悶的C小加(二)
時間限制:1000 ms | 內存限制:65535 KB
難度:4
- 描述
-
聰明的你幫助C小加解決了中綴表達式到后綴表達式的轉換(詳情請參考“郁悶的C小加(一)”),C小加很高興。但C小加是個愛思考的人,他又想通過這種方法計算一個表達式的值。即先把表達式轉換為后綴表達式,再求值。這時又要考慮操作數是小數和多位數的情況。
- 輸入
-
第一行輸入一個整數T,共有T組測試數據(T<10)。
每組測試數據只有一行,是一個長度不超過1000的字符串,表示這個運算式,每個運算式都是以“=”結束。這個表達式里只包含+-*/與小括號這幾種符號。其中小括號可以嵌套使用。數據保證輸入的操作數中不會出現負數並且小於1000000。
數據保證除數不會為0。 - 輸出
- 對於每組測試數據輸出結果包括兩行,先輸出轉換后的后綴表達式,再輸出計算結果,結果保留兩位小數。兩組測試數據之間用一個空行隔開。
- 樣例輸入
-
2 1+2= (19+21)*3-4/5=
- 樣例輸出
-
12+= 3.00 1921+3*45/-= 119.20
-
1 #include<stdio.h> 2 #include<string.h> 3 #include<stack> 4 #include<stdlib.h> 5 using namespace std; 6 7 char a[1010]; 8 char b[1010]; 9 stack <char> s1; 10 stack <float> s2; 11 12 int i,j,n,m,t; 13 float x,y,z; 14 15 int fun(char x) 16 { 17 switch(x) 18 { 19 case '+' : 20 case '-' :return 1; 21 case '*' : 22 case '/' :return 2; 23 case '(' :return 0; 24 default :return -1; 25 } 26 } 27 28 float js(float x,float y,char z) 29 { 30 switch(z) 31 { 32 case '+':return y+x; 33 case '-':return y-x; 34 case '*':return y*x; 35 default :return y/x; 36 } 37 } 38 39 int main() 40 { 41 int p; 42 char c[1010]; 43 float d; 44 scanf("%d",&t); 45 s1.push('#'); 46 while(t--) 47 { 48 j=0; 49 scanf("%s",a); 50 m=strlen(a)-1; 51 for(i=0;i<m;i++) 52 { 53 if(a[i]>='0'&&a[i]<='9'||a[i]=='.') 54 { 55 memset(c,0,sizeof(c)); 56 p=0; 57 while(a[i]>='0'&&a[i]<='9'||a[i]=='.') 58 { 59 b[j++]=a[i]; 60 c[p++]=a[i++]; 61 } 62 d=atof(c); 63 s2.push(d); 64 i--; 65 } 66 67 else if(a[i]=='(') s1.push(a[i]); 68 69 else if(a[i]==')') 70 { 71 while(s1.top()!='(') 72 { 73 b[j++]=s1.top(); 74 x=s2.top();s2.pop(); 75 y=s2.top();s2.pop(); 76 x=js(x,y,b[j-1]); 77 s2.push(x); 78 s1.pop(); 79 } 80 s1.pop(); 81 } 82 83 else 84 { 85 while(fun(s1.top())>=fun(a[i])) 86 { 87 b[j++]=s1.top(); 88 x=s2.top();s2.pop(); 89 y=s2.top();s2.pop(); 90 x=js(x,y,b[j-1]); 91 s2.push(x); 92 s1.pop(); 93 } 94 s1.push(a[i]); 95 } 96 } 97 98 while(s1.top()!='#') 99 { 100 b[j++]=s1.top(); 101 x=s2.top();s2.pop(); 102 y=s2.top();s2.pop(); 103 x=js(x,y,b[j-1]); 104 s2.push(x); 105 s1.pop(); 106 } 107 b[j]='='; 108 b[j+1]='\0'; 109 puts(b); 110 printf("%.2f\n",s2.top()); 111 s2.pop(); 112 } 113 return 0; 114 }