HDU 1237

数据结构栈表达式求值
#include<stdio.h>
#include<string.h>
#include<math.h>
#include<algorithm>
#include <iostream>
#include<queue>
#include<stack>
#include<string>
using namespace std;
stack<double> data;
stack<char> ope;
int main()
{
    string a;
    while(getline(cin,a),!((a.size()==1)&&a[0] =='0'))
    {
        for(int i=0;i<a.size();i++)
        {
            if(a[i]==' ')
                a.erase(i,1);
        }
        for(int i=0;i<a.size();)
        {
            double data1=0;
            int wei = 10;

            if(a[i]>='0'&&a[i]<='9')
            {
            data1=0;

            while(a[i]>='0'&&a[i]<='9')
            {
                //cout<<i<<endl;
                data1*=10;
                data1 += (a[i]-'0');
                i++;
            }
            //cout<<data1<<endl;
            data.push(data1);
            }
            else
            //cout<<data.top()<<endl;
                ope.push(a[i++]);
         //   cout<<ope.top()<<endl;

            if((!ope.empty())&&ope.top()=='*')
            {
                data1=0;
                wei = 1;
                while(a[i]>='0'&&a[i]<='9')
                {

                    data1*=10;
                    data1 += (a[i]-'0');
                    i++;
                }


                double aa;
                aa = data1*data.top();
                data.pop();
                data.push(aa);
                ope.pop();
                //ope.push('+');
            }

            if((!ope.empty())&&ope.top()=='/')
            {
                data1=0;
                wei = 1;
                while(a[i]>='0'&&a[i]<='9')
                {
                    data1*=10;
                    data1 += (a[i]-'0');
                    i++;
                }
                double aa;
                aa = data.top()/data1;
                data.pop();
                data.push(aa);
                ope.pop();
                //ope.push('+');
            }

        }
        //cout<<"ok\n";
        if(!ope.empty()&&ope.top()=='\n') ope.pop();
        //cout<<ope.top()<<endl;
        double ans = 0;
        while(!ope.empty())
        {
            if(ope.top()=='+')
            {
                ans += data.top();
                ope.pop();
                data.pop();
            }
            else if(ope.top()=='-')
            {
                ans -= data.top();
                ope.pop();
                data.pop();
            }
            //cout<<ope.size()<<endl;
        }
        ans += data.top();
        printf("%.2lf\n",ans);
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值