码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1237

时间:2015-06-19 22:53:30      阅读:202      评论:0      收藏:0      [点我收藏+]

标签:

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==\n) 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() == \n) 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\n", s2.top());
    }
    return 0;
}
View Code

 

HDU 1237

标签:

原文地址:http://www.cnblogs.com/xiaohongmao/p/4589775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!