• HDU 1237


    http://acm.hdu.edu.cn/showproblem.php?pid=1237

    表达式计算,方法是中缀转后缀,再计算。中间处理用栈操作

    讲解看http://blog.csdn.net/antineutrino/article/details/6763722

    这题是简易版本的,不用处理括号

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <stack>
    
    using namespace std;
    
    int cmp(char a, char b) {
        if((a == '*' || a == '/') && (b == '+' || b == '-')) return 1;
        return 0;
    }
    
    double cal(double a, double b, char c) {
        if(c == '+') return a + b;
        if(c == '-') return a - b;
        if(c == '*') return a * b;
        if(c == '/') return a / b;
    }
    
    int main() {
        double a;
        while(~scanf("%lf", &a)) {
            char c;
            c = getchar();
            stack <char> s1;
            stack <double> s2;
            if(!a && c=='
    ') break;
            s2.push(a);
            c = getchar(); 
            while(~scanf("%lf", &a)) {
                if(s1.empty()) {
                    s1.push(c);
                }
                else {
                    if(cmp(c, s1.top())) s1.push(c);
                    else {
                        while(1) {
                            double t1 = s2.top();
                            s2.pop();
                            double t2 = s2.top();
                            s2.pop();
                            char t3 = s1.top();
                            s1.pop();
                            double t4 = cal(t2, t1, t3);
                            s2.push(t4);
                            if(s1.empty() || cmp(c, s1.top())) {
                                s1.push(c);
                                break;
                            }
                        }
                    }
                }
                s2.push(a);
                if(getchar() == '
    ') break;
                c = getchar();
            }
            while(!s1.empty()) {
                double t1 = s2.top();
                s2.pop();
                double t2 = s2.top();
                s2.pop();
                char t3 = s1.top();
                s1.pop();
                double t4 = cal(t2, t1, t3);
                s2.push(t4);
            }
            printf("%.2lf
    ", s2.top());
        }
        return 0;
    }
    View Code
  • 相关阅读:
    POJ 1953 World Cup Noise
    POJ 1995 Raising Modulo Numbers (快速幂取余)
    poj 1256 Anagram
    POJ 1218 THE DRUNK JAILER
    POJ 1316 Self Numbers
    POJ 1663 Number Steps
    POJ 1664 放苹果
    如何查看DIV被设置什么CSS样式
    独行DIV自适应宽度布局CSS实例与扩大应用范围
    python 从入门到精通教程一:[1]Hello,world!
  • 原文地址:https://www.cnblogs.com/xiaohongmao/p/4589775.html
Copyright © 2020-2023  润新知