HDU1237 简单计算器【堆栈】

简单计算器

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

Total Submission(s): 21518    Accepted Submission(s): 7722
Problem Description
读入一个只包含 +, -, *, / 的非负整数计算表达式,计算该表达式的值。
Input
测试输入包含若干测试用例,每个测试用例占一行,每行不超过200个字符,整数和运算符之间用一个空格分隔。没有非法表达式。当一行中只有0时输入结束,相应的结果不要输出。
Output
对每个测试用例输出1行,即该表达式的值,精确到小数点后2位。
Sample Input
1 + 2 4 + 2 * 5 - 7 / 11 0
Sample Output
3.00 13.36
Source


问题链接HDU1237 简单计算器

问题描述参见上文。

问题分析这是一个表达式求值问题,可以用递归来处理,也可以用堆栈来处理。

程序说明:程序中,使用堆栈来处理运算符的优先级,运算符和操作符分别放在两个堆栈中。

参考链接:(略)



AC的C++语言程序:

/* HDU1237 简单计算器 */

#include <iostream>
#include <string>
#include <stack>
#include <cctype>
#include <cstdio>

using namespace std;

int main()
{
    string s;
    stack<char> op;
    stack<double> operand;
    double operand1, operand2;

    while(getline(cin, s) && s != "0") {
        for(int i=0; s[i]; i++) {
            if(isdigit(s[i])) {
                operand1 = 0;
                while(isdigit(s[i])) {
                    operand1 = operand1 * 10 + s[i] - '0';
                    i++;
                }
                i--;
                operand.push(operand1);
            } else if(s[i] == '+' || s[i] == '-') {
                if(op.empty())
                    op.push(s[i]);
                else {
                    char sop = op.top();
                    op.pop();
                    operand2 = operand.top();
                    operand.pop();
                    operand1 = operand.top();
                    operand.pop();
                    if(sop == '+')
                        operand.push(operand1 + operand2);
                    else
                        operand.push(operand1 - operand2);
                    op.push(s[i]);
                }
            } else if(s[i] == '*' || s[i] == '/') {
                char cop = s[i];
                i += 2;
                operand2 = 0;
                while(isdigit(s[i])) {
                    operand2 = operand2 * 10 + s[i] - '0';
                    i++;
                }
                i--;
                operand1 = operand.top();
                operand.pop();
                if(cop == '*')
                    operand.push(operand1 * operand2);
                else
                    operand.push(operand1 / operand2);
            }
        }

        while(!op.empty()) {
            char sop = op.top();
            op.pop();
            operand2 = operand.top();
            operand.pop();
            operand1 = operand.top();
            operand.pop();
            if(sop == '+')
                operand.push(operand1 + operand2);
            else
                operand.push(operand1 - operand2);
        }

        printf("%.2f\n", operand.top());
    }

    return 0;
}


posted on 2017-05-14 11:06  海岛Blog  阅读(210)  评论(0编辑  收藏  举报

导航