1. 程式人生 > >求字首表示式的值

求字首表示式的值

算術表示式有字首表示法、中綴表示法和字尾表示法等形式。字首表示式指二元運算子位於兩個運算數之前,例如2+3*(7-4)+8/4的字首表示式是:+ + 2 * 3 - 7 4 / 8 4。請設計程式計算字首表示式的結果值。

輸入格式:

輸入在一行內給出不超過30個字元的字首表示式,只包含+-*\以及運算數,不同物件(運算數、運算子號)之間以空格分隔。

輸出格式:

輸出字首表示式的運算結果,保留小數點後1位,或錯誤資訊ERROR

輸入樣例:

+ + 2 * 3 - 7 4 / 8 4

輸出樣例:

13.0

 千萬不要忘了小數的情況,用atof來將字串轉換成浮點數。

#include<bits/stdc++.h>
using namespace std;

void infix(vector<string> v)
{
    stack<double> stac;
    double a,b;
    for(int i=v.size()-1;i>=0;i--)
    {
        if(v[i]=="+")
        {
            a=stac.top();
            stac.pop();
            b=stac.top();
            stac.pop();
            stac.push(a+b);
        }
        else if(v[i]=="-")
        {
            a=stac.top();
            stac.pop();
            b=stac.top();
            stac.pop();
            stac.push(a-b);
        }
        else if(v[i]=="*")
        {
            a=stac.top();
            stac.pop();
            b=stac.top();
            stac.pop();
            stac.push(a*b);
        }
        else if(v[i]=="/")
        {
            a=stac.top();
            stac.pop();
            if(stac.top()==0 || stac.empty()) {cout<<"ERROR"<<endl;exit(0);}
            else b=stac.top();
            stac.pop();
            stac.push(a/b);
        }
        else{
            stac.push(atof(v[i].c_str()));
        }
    }
    printf("%.1f\n",stac.top());
}
int main()
{
    vector<string> v;
    string s;
    while(cin>>s)
    {
        v.push_back(s);
    }
    infix(v);
    return 0;
}