PAT (解題報告) 7-4 求字首表示式的值 (25 分)
阿新 • • 發佈:2018-12-14
算術表示式有字首表示法、中綴表示法和字尾表示法等形式。字首表示式指二元運算子位於兩個運算數之前,例如2+3*(7-4)+8/4
的字首表示式是:+ + 2 * 3 - 7 4 / 8 4
。請設計程式計算字首表示式的結果值。
輸入格式:
輸入在一行內給出不超過30個字元的字首表示式,只包含+
、-
、*
、\
以及運算數,不同物件(運算數、運算子號)之間以空格分隔。
輸出格式:
輸出字首表示式的運算結果,保留小數點後1位,或錯誤資訊ERROR
。
輸入樣例:
+ + 2 * 3 - 7 4 / 8 4
輸出樣例:
13.0
#include<iostream> #include<vector> #include<cstdio> #include<set> #include<map> #include<string> #include<string.h> #include<algorithm> #include<cmath> #include<stdlib.h> #include<ctype.h> #include<stack> #include<queue> #include<list> using namespace std; stack<double>st1; int main(){ char c; char ch[20005]; int i=0,cc=1; while((c=getchar())!= '\n'){ ch[i++] = c; } for(int j=i-1; j>=0; j--){ if(ch[j]==' ') continue; if(ch[j]>='0' && ch[j]<='9'){ double mul = 10, num = ch[j] - '0'; for (j--; j >= 0; j--) { if (ch[j]>='0' && ch[j]<='9') { num += (ch[j] - '0') * mul; mul *= 10; } else if (ch[j] == '.') { num /= mul; mul = 1; } else if (ch[j] == '-') num = -num; else break; } st1.push(num); } else{ double temp = st1.top(); st1.pop(); if(ch[j]=='*'){ temp *= st1.top(); st1.pop(); } else if(ch[j]=='/'){ if(st1.top()==0){ cout<<"ERROR"<<endl; return 0; } temp /= st1.top(); st1.pop(); } else if(ch[j]=='+'){ temp += st1.top(); st1.pop(); } else{ temp -= st1.top(); st1.pop(); } st1.push(temp); } } printf("%.1lf",st1.top()); return 0; }
思路: 首先,我們想問題要全面,度提要仔細!!!
1、題目中沒有明確說明是整數,而且也沒說是正數,所以我們必須考慮 小數 和負數 的情況 !
2、因為是按字元輸入,例如小數3.2 的格式為3.2,這裡‘.’的前後是沒有空格的!我們讀取從右至左,所以會先讀到2然後是‘.’,最後是3;我們只需要讓2變成0.2;加上3就搞定了!!!
3、負數:例如-1 格式是就是-1 中間也沒有空格;有空格一定是-。我們遍歷時如果遇到數字和‘-’挨著,那麼就一定是負數!!!
4、這兩種特殊資料處理完就按照計算字首表示式的正常的步驟處理就ok;