HDU - 1237 - 简单计算器(栈)

HDU 1237.简单计算器

Time Limit: 2000/1000 MS (Java/Others)      Memory Limit: 65536/32768 K (Java/Others)

Problem Description

读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。

Input

测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。

Output

对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。

Sample Input

1 + 2
4 + 2 * 5 - 7 / 11
0

Sample Output

3.00
13.36

思路:栈的应用,因为运算有优先级,在刚开始考虑乘法和除法,如果运算符是加法,则直接把那个数字压入栈里,如果是减法,则把那个数的相反数压入栈里,如果是乘法,则取栈头的数相乘,pop出后把结果push进去,除法同理,最后就把栈中的数字相加就是结果(!!注意表达式中间有空格)


#include<cstdio>
#include<cstring>
#include<algorithm>
#include<stack> 
using namespace std;
stack<double>num;

int main() {
    int n, i;
    while(scanf("%d", &n)){
        char c;
        c = getchar();
        if(c=='\n' && n==0)
            break;
        num.push(n);
        c = getchar(); 
        double m;
        while(scanf("%d", &n)){
            if(c == '*'){
                m = num.top();
                m*=n;
                num.pop();
                num.push(m);    
            }
            else if(c == '/'){
                m = num.top();
                m/=n;
                num.pop();
                num.push(m);
            }
            else if(c == '+'){
                num.push(n);
            }
            else if(c == '-'){
                num.push(0-n);
            }
            if(getchar()=='\n')    //本行输入完毕 
                break;
            c = getchar();
        } 
        double sum = 0;
        while(!num.empty()){
            sum+=num.top();
            num.pop();         //使用完后栈一定要清空
        }
        printf("%.2lf\n", sum);

    } 
    return 0;
}

你可能感兴趣的:(栈,杭电)