HDU 1237 - 簡(jiǎn)單計(jì)算器 表達(dá)式求值

讀入一個(gè)只包含 +, -, *, / 的非負(fù)整數(shù)計(jì)算表達(dá)式,計(jì)算該表達(dá)式的值。

Input

測(cè)試輸入包含若干測(cè)試用例,每個(gè)測(cè)試用例占一行,每行不超過(guò)200個(gè)字符,整數(shù)和運(yùn)算符之間用一個(gè)空格分隔。沒(méi)有非法表達(dá)式。當(dāng)一行中只有0時(shí)輸入結(jié)束,相應(yīng)的結(jié)果不要輸出。

Output

對(duì)每個(gè)測(cè)試用例輸出1行,即該表達(dá)式的值,精確到小數(shù)點(diǎn)后2位。

Sample Input

1 + 2
4 + 2 * 5 - 7 / 11
0

Sample Output

3.00
13.36

中綴表達(dá)式轉(zhuǎn)后綴表達(dá)式然后求值 具體步驟可以參考http://www.itdecent.cn/p/d7df4812a981

#include <iostream>
#include <cstdio>
#include <cstring>
#include<stack>
using namespace std;

int P(char c)
{
    if (c == '+' || c == '-') return 1;
    return 2;
}

double Ans(double x, double y, char c)
{
    if (c == '+') return x + y;
    if (c == '-') return x - y;
    if (c == '*')return x*y;
    return x / y;

}
int main() {
    int n;
    while (scanf("%d",&n)!=EOF)
    {
        char c = getchar();
        if (c=='\n'&&n == 0)break;
        stack<char> op;
        stack<double>num;
        num.push(n);
        while (true)
        {
            scanf("%c %d", &c, &n);
            char k = getchar();
            while (!op.empty()&&P(c)<=P(op.top()))
            {
                char t = op.top();
                op.pop();
                double y = num.top();
                num.pop();
                double x = num.top();
                num.pop();
                double ans = Ans(x, y, t);
                num.push(ans);
            }
            op.push(c);
            num.push(n);
            if (k == '\n')break;

        }
        while (!op.empty())
        {
            char t = op.top();
            op.pop();
            double y = num.top();
            num.pop();
            double x = num.top();
            num.pop();
            double ans = Ans(x, y, t);
            num.push(ans);
        }
        printf("%.2f\n", num.top());
    }
    return 0;
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書(shū)系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容