標籤:style io os 使用 ar sp 問題 on c
一個模板了 哈哈.
這題因為已經包含了整形、浮點形了,以後也不需要特別處理了。
/*這裡主要是逆波蘭式的實現,使用兩個stack 這裡用字串來類比一個stack,第一步,將中綴運算式轉變為尾碼運算式第二步,然後再使用一個stack,計算尾碼運算式的結果,這一步很容易出錯,考慮到浮點數的問題。*/#include <iostream>#include <string>#include <cstring>#include <cstdio>#include <stack>#include <iomanip>using namespace std;int cmp(char ch) // 運算子優先順序{switch(ch){case '+':case '-': return 1;case '*':case '/': return 2;default : return 0;}}void change(char *s1,char *s2) // 中綴運算式轉變尾碼運算式{stack <char> s;s.push('#');int i = 0,len=strlen(s1),cnt=0;while(i < len-1) //現在輸入的是1.000 +2 /4=,如果是1.000+2/4的話需要把-1去掉{ if(s1[i]==' ') { i++; continue; }else if(s1[i] == '('){s.push(s1[i++]);}else if(s1[i] == ')'){while(s.top() != '('){ s2[cnt++]=s.top();s2[cnt++]= ' ';s.pop();}s.pop();i++;}else if(s1[i] == '+'||s1[i] == '-'||s1[i] == '*'||s1[i] == '/'){while(cmp(s.top()) >= cmp(s1[i])){s2[cnt++]=s.top();s2[cnt++]= ' ';s.pop();}s.push(s1[i]);i++;}else{while('0' <= s1[i]&&s1[i] <= '9'||s1[i] == '.'){ s2[cnt++]=s1[i++];} s2[cnt++]= ' ';}}while(s.top() != '#'){s2[cnt++]=s.top(); s2[cnt++]= ' ';s.pop();}s2[cnt]='\0';}double value(char *s2) // 計算尾碼運算式,得到其結果。{stack < double> s;double x,y;int i = 0,len=strlen(s2);while(i < len){if(s2[i] == ' '){i++;continue;}switch(s2[i]){case '+': x = s.top(); s.pop(); x += s.top(); s.pop(); i++; break;case '-': x = s.top(); s.pop(); x =s.top()-x; s.pop(); i++; break;case '*': x = s.top(); s.pop(); x *= s.top(); s.pop(); i++; break;case '/': x = s.top(); s.pop(); x = s.top()/x; s.pop(); i++; break;default :{x = 0;while('0' <= s2[i]&&s2[i] <= '9'){x = x*10+s2[i] - '0';i++;}if(s2[i] == '.'){double k = 10.0;y = 0;i++;while('0' <= s2[i]&&s2[i] <= '9'){y += ((s2[i]-'0')/k);i++;k *= 10;}x += y;}}}s.push(x);}return s.top();}char s1[1006],s2[1006];int main(){int n;scanf("%d",&n);getchar();while(n--){gets(s1);change(s1,s2);printf("%.2f\n",value(s2));}return 0;}/*21.000 +2 / 4=((1+2 )* 5+1) /4=*/
NYOJ 35 運算式求值