栈 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;
}


你可能感兴趣的:(栈 hdu1237 简单计算器)