栈 hdu1237 简单计算器

用栈来处理简单的表达式非常好,但是比较复杂的表达式就有些不适用了


如果符号是+,-直接压入栈,符号压入的时候改变符号

如果是* / 后面一个数字是x,取出栈顶,设为y,然后运算x,比如y=y/x,或者y=y*x

再把y压入栈中


最后把栈里面的全部取出加起来,就是答案了

#include<cstdio>
#include<cmath>
#include<cstring>
#include<queue>
#include<cctype>
#include<stack>
#include<vector>
#include<functional>
#include<algorithm>

using namespace std;
typedef long long LL;
typedef pair<int, int> PII;

const int MX = 20000 + 5;
const int INF = 0x3f3f3f3f;

char S[MX];

int main() {
    while(gets(S + 1)) {
        int N = strlen(S + 1);

        if(S[1] == '0' && N == 1) break;

        char op = '+';
        int x = 0;
        stack<double>work;
        for(int cur = 1; cur <= N; cur++) {
            while(S[cur] == ' ') cur++;
            while(isdigit(S[cur])) {
                x = x * 10 + S[cur] - '0';
                cur++;
            }

            double last;
            switch(op) {
            case '+':
                work.push(x);
                break;
            case '-':
                work.push(-x);
                break;
            case '*':
                last = work.top();
                work.pop();
                work.push(last * x);
                break;
            case '/':
                last = work.top();
                work.pop();
                work.push(last / x);
                break;
            }

            while(S[cur] == ' ') cur++;
            op = S[cur];
            x = 0;
        }

        double ans = 0;
        while(!work.empty()) {
            ans += work.top();
            work.pop();
        }

        printf("%.2lf\n", ans);
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值