nyoj35——表达式求值

这道题是一道很好的数据结构题目,会用到栈,需要弄清楚后缀表达式。




#include <stack>
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#include <stdlib.h>

using namespace std;

int priority(char c)//优先级
{
    if(c == '=')    return 0;
    if(c == '+')    return 1;
    if(c == '-')    return 1;
    if(c == '*')    return 2;
    if(c == '/')    return 2;
    return 0;
}

void compute(stack<double>& Num,stack<char>& Op)//根据不同的运算符计算出两个数的值
{
    double b = Num.top();
    Num.pop();
    double a = Num.top();
    Num.pop();
    switch(Op.top())
    {
    case '+':
        Num.push(a+b);
        break;
    case '-':
        Num.push(a-b);
        break;
    case '*':
        Num.push(a*b);
        break;
    case '/':
        Num.push(a/b);
        break;
    }
    Op.pop();
}

int main()
{
    int z;
    char str[1005];
    stack<double> Num;
    stack<char> Op;
    scanf("%d",&z);
    while(z--)
    {
        scanf("%s",str);
        int len = strlen(str);
        for(int i=0; i<len; i++)
        {
            if(isdigit(str[i]))//如果是数字
            {
                double n = atof(&str[i]);
                while(i<len && (isdigit(str[i]) || str[i]=='.'))
                    i++;
                i--;
                Num.push(n);//将数字压入值栈
            }
            else
            {
                if(str[i] == '(')//如果是左括号
                    Op.push(str[i]);//直接入栈
                else if(str[i] == ')')//如果是右括号
                {
                    while(Op.top()!='(')//将运算符栈里面的运算符弹出来,直到为左括号结束
                        compute(Num,Op);//进行运算
                    Op.pop();//将左括号弹出
                }
                else if(Op.empty() || priority(str[i])>priority(Op.top()))//如果运算符栈为空或者当前运算符的优先级大于栈顶运算符的优先级,直接入栈
                    Op.push(str[i]);
                else
                {
                    while(!Op.empty() && priority(str[i])<=priority(Op.top()))//如果栈不为空且当前运算符的优先级小于或等于栈顶运算符的优先级,先将栈里面的运算符进行运算
                        compute(Num,Op);
                    Op.push(str[i]);//然后入栈
                }
            }
        }
        Op.pop();
        printf("%.2f\n",Num.top());
        Num.pop();
    }
    return 0;
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值