hdu_1237_栈_计算式子

/*
开两个栈,一个保存运算符,一个保存数字,每遇到一个运算符,就与栈顶的运算符进行
比较优先级...
*/
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<stack>
using namespace std;

char s[300];

int priority(char a,char b)   // 优先级
{
    int x,y;
    if(a=='+'||a=='-')
        x=1;
    else
        x=2;
    if(b=='+'||b=='-')
        y=1;
    else
        y=2;
    return x-y;
}

double cal(double a,double b,char x)    // 计算
{
    switch(x)
    {
    case '+':return a+b;break;
    case '-':return a-b;break;
    case '*':return a*b;break;
    case '/':return a/b;break;
    }
}

int main()
{
    while(gets(s))
    {
        double a,b;
        int len=strlen(s);
        if(len==1&&s[0]=='0')
            break;
        stack<double>num;
        stack<char>oper;
        int i,j;
        for(i=0;i<len;i++)
        {
            if(s[i]>='0'&&s[i]<='9')
            {
                a=(double)(s[i]-'0');
            while(i+1<len&&s[i+1]!=' ')
            {
                i++;
                a=a*10+s[i]-'0';
            }
                num.push(a);
            }
            else if(s[i]!=' ')
            {
                if(!oper.empty())
                {
                    if(priority(oper.top(),s[i])>=0)
                    {
                        a=num.top();
                        num.pop();
                        b=num.top();
                        num.pop();
                        num.push(cal(b,a,oper.top()));
                        oper.pop();
                        oper.push(s[i]);
                    }
                    else
                    {
                        a=num.top();
                        num.pop();
                        b=(double)(s[i+2]-'0');
                        char x=s[i];
                        i+=2;
                        while(i+1<len&&s[i+1]!=' ')
                        {
                         i++;
                         b=b*10+s[i]-'0';
                        }
                        num.push(cal(a,b,x));
                    }
                }
                else
                    oper.push(s[i]);
            }
        }
        if(!oper.empty())
        {
            a=num.top();
            num.pop();
            b=num.top();
            printf("%.2lf/n",cal(b,a,oper.top()));
        }
        else
        printf("%.2lf/n",num.top());
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值