逆波蘭表達式求值 解題報告

逆波蘭表示法是一種將運算符(operator)寫在操作數(operand)後面的描述程序(算式)的方法。舉個例子,我們平常用中綴表示法描述的算式(1 + 2)*(5 + 4),改爲逆波蘭表示法之後則是1 2 + 5 4 + *。相較於中綴表示法,逆波蘭表示法的優勢在於不需要括號。
請輸出以逆波蘭表示法輸入的算式的計算結果。

輸入格式:

在一行中輸入1個算式。相鄰的符號(操作數或運算符)用1個空格隔開。

輸出格式:

在一行中輸出計算結果。

限制:

2≤算式中操作數的總數≤100
1≤算式中運算符的總數≤99
運算符僅包括“+”、“-”、“*”,操作數、計算過程中的值以及最終的計算結果均在int範圍內。

輸入樣例1:

4 3 + 2 -

輸出樣例1:

5

輸入樣例2:

1 2 + 3 4 - *

輸出樣例2:

-3

 思路:咳咳就不說我爲啥沒拿滿分了,我自己至今不明白當時自己的腦回路是什麼。

這道題就是遇到符號就彈出兩個數,特別注意的是小數問題,再就是不輸出多餘的0。

下面給出AC代碼:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int INF=0x3f3f3f3f;
const int maxn=500+10;
stack<double> s;
string str;

int main()
{
    getline(cin,str);
    for(int i=0; i<str.size(); i++)
    {

        if(str[i]==' ') continue;
        else if(str[i]=='+')
        {
            double t=s.top();
            s.pop();
            double tt=s.top();
            s.pop();
            s.push(t+tt);
        }
        else if(str[i]=='*')
        {
            double t=s.top();
            s.pop();
            double tt=s.top();
            s.pop();
            s.push(t*tt);
        }
        else if(str[i]=='-')
        {
            double t=s.top();
            s.pop();
            double tt=s.top();
            s.pop();
            s.push(tt-t);
        }
        else
        {
            double ans=0,ans1=0;
            int j;
            for(j=i;j<str.size();j++)
            {
                if(str[j]=='.'||str[j]==' ') break;
                ans=ans*10+str[j]-'0';
            }

            if(str[j]=='.')
            {
                double t=0.1;
                for(j=j+1; j<str.size(); j++)
                {
                    if(str[j]==' ') break;
                    ans1+=(str[j]-'0')*t;
                    t*=0.1;
                }
            }
            //cout<<"G  "<<ans<<"    "<<ans1<<endl;

            i=j;
            s.push(ans+ans1);
        }
    }

    printf("%g",s.top());
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章