HDU1237 简单计算器【堆栈】

来源:互联网 发布:网络歌手樊棋照片 编辑:程序博客网 时间:2024/05/16 16:19

简单计算器

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 + 24 + 2 * 5 - 7 / 110
Sample Output
3.0013.36
Source
浙大计算机研究生复试上机考试-2006年


问题链接: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;}


1 0
原创粉丝点击