NYOJ35 表达式求值【栈】

表达式求值
时间限制:3000 ms  |  内存限制:65535 KB 
难度:4

描述 
ACM队的mdd想做一个计算器,但是,他要做的不仅仅是一计算一个A+B的计算器,他想实现随便输入一个表达式都能求出它的值的计算器,现在请你帮助他来实现这个计算器吧。

比如输入:“1+2/4=”,程序就输出1.50(结果保留两位小数) 


输入 
第一行输入一个整数n,共有n组测试数据(n<10)。
每组测试数据只有一行,是一个长度不超过1000的字符串,表示这个运算式,每个运算式都是以“=”结束。这个表达式里只包含+-*/与小括号这几种符号。其中小括号可以嵌套使用。数据保证输入的操作数中不会出现负数。

数据保证除数不会为0 


输出 

每组都输出该组运算式的运算结果,输出结果保留两位小数。 


样例输入 
2
1.000+2/4=

((1+2)*5+1)/4=


样例输出 

1.50

4.00


来源 

数据结构课本例题改进 


上传者 

张云聪


题目大意:给你一个计算表达式,求出最终结果。

思路:用两个栈来分别存数和操作符, 遇到'(',操作符入栈,遇到')',计算括号内的

式子。遇到'+'、'-'、'*'、'/'就比较当前运算符与栈中运算符的优先级,大于等于于栈

中优先级就计算,否则就入栈,留待下次计算。最后计算栈中剩下优先级低的相应式子


#include<iostream>
#include<algorithm>
#include<stack>
#include<string>
#include<cstring>
#include<cstdio>
using namespace std;

stack<double> num;
stack<char> oper;
char a[1010],buf[1010];

int CmpValue(char op)
{
    if(op=='(' )
        return 0;
    if(op=='+' || op=='-')
        return 1;
    if(op=='*' || op=='/')
        return 2;
}
void calc()
{
    double x,y;
    char op;
    if(num.size()>=2 && !oper.empty())
    {
        y = num.top();
        num.pop();
        x = num.top();
        num.pop();
        op = oper.top();
        if(op=='+')
            num.push(x+y);
        else if(op=='-')
            num.push(x-y);
        else if(op=='*')
            num.push(x*y);
        else if(op=='/')
            num.push(x/y);
        oper.pop();
    }
}

int main()
{

    int N;
    cin >> N;
    while(N--)
    {
        memset(a,0,sizeof(a));
        memset(buf,0,sizeof(buf));
        scanf("%s",a);
        int i = 0;
        while(1)
        {
            if(isalnum(a[i]))
            {
                double d;
                sscanf(a+i,"%lf",&d);
                num.push(d);
                while(isalnum(a[i]) || a[i]=='.')
                    i++;
            }
            char c = a[i++];
            if(c=='=' || c=='\0')
                break;
            if(c=='(')
                oper.push(c);
            else if(c==')')
            {
                while(!oper.empty())
                {
                    if(oper.top()=='(')
                    {
                        oper.pop();
                        break;
                    }
                    calc();
                }
            }
            else
            {
                while(!oper.empty() && CmpValue(c) <= CmpValue(oper.top()))
                {
                    calc();
                }
                oper.push(c);
            }

        }
        while(!oper.empty())
            calc();
        printf("%.2lf\n",num.top());
        while(num.empty())
            num.pop();
    }

    return 0;
}



你可能感兴趣的:(NYOJ35 表达式求值【栈】)