NYOJ 35 運算式求值

來源:互聯網
上載者:User

標籤: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 運算式求值

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.