hdu1237计算器
简单计算器
Time Limit: 2000/1000 MS (Java/Others)  Memory Limit: 65536/32768 K (Java/Others)
Total Submission(s): 36334  Accepted Submission(s): 13065
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
解题思路:
主要是采取了两个栈来保存操作符和运算数字。
另外:亮点在于P(c) < P(op.top())这里的优先级比较:
我们可以发现通过表格或者其他的形式可以看出在运算优先级的问题上,我们只有采取这样的策略才是最好的。
当前的优先级高那么压入栈,当前优先级和栈顶(上次的)的优先级相同,或小于上次的话,自然时先算上次的,同时这样的模拟也是最符合我们自己的真实的运算过程的。
#include<bits/stdc++.h>
using namespace std;
int P(char c)
{
    if (c == '+' || c == '-') return 1;
    return 2;
}
double Ans(double x, double y, char c)
{
    if (c == '+') return x + y;
    if (c == '-') return x - y;
    if (c == '*')return x*y;
    return x / y;
}
int main() {
    int n;
    while (~scanf("%d",&n))
    {
        char c = getchar();
        if (c=='\n'&&n == 0)break;
        stack<char> op;
        stack<double>num;
        num.push(n);
        while (true)//开始一行的运算,之前已经获取了一个n,并压入num;
        {
            scanf("%c %d", &c, &n);
            char k = getchar();
            while (!op.empty()&&P(c)<=P(op.top()))//第一次会跳过
            //当操作符的栈不为空……且现在的操作符优先级小于或等于栈顶的的操作符的优先级时
            //那么先将之前的进行计算
            {
                char t = op.top();
                op.pop();
                double y = num.top();
                num.pop();
                double x = num.top();
                num.pop();
                double ans = Ans(x, y, t);
                num.push(ans);
            }
            op.push(c);
            num.push(n);
            if (k == '\n')break;
            //这导致了上面还有压入的数字和操作符未被操作,便有了下面的判断op栈
        }
        while (!op.empty())
        {
            char t = op.top();
            op.pop();
            double y = num.top();
            num.pop();
            double x = num.top();
            num.pop();
            double ans = Ans(x, y, t);
            num.push(ans);
        }
        printf("%.2f\n", num.top());
    }
    return 0;
}