zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    C++primer习题3.13
    Indesign技巧
    《转载》虚函数在对象中的内存布局
    C++new失败后如何处理
    sizeof的用法
    转载 C++中虚继承防止二义性
    字符串反转
    回文写法
    C++术语
    QT+VS2008
  • 原文地址:https://www.cnblogs.com/xiaohongmao/p/4589775.html
Copyright © 2011-2022 走看看