HDU 1237 简单计算器 (栈 )

 

 

#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<stack>
using namespace std;
char str[300];
double ans;
double chcd(char x)
{
    return (x-'0')*1.0;
}
double ch(int l,int r)
{
    //printf("%d %d\n",l,r);
    double ret=0;
    int wei=1;
    int i;
    for(i=r-1;i>=l;i--)
    {
        double now=chcd(str[i]);
        ret+=wei*now;
        wei*=10;
    }
    return ret;
}
int getr(int l)
{
    while('0'<=str[l]&&str[l]<='9') l++;
    return l;
}
void fun()
{
    stack<double> num;
    stack<char>   op;
    int i,j,k;
    int l=0,r=0;
    int len=strlen(str);
    double now,next;
    r=getr(l);
    now=ch(l,r);
    num.push(now);
    int cnt=1;
    for(i=r+1;i<len;i++)
    {
       //now=ch(str[i]);
       //printf("%d.  %.0lf\n",cnt++,now);
       if(str[i]=='*')
       {
           now=num.top();
           r=getr(i+2);
           next=ch(i+2,r);
           num.pop();
           now*=next;
           num.push(now);

       }
       else if(str[i]=='/')
       {
           now=num.top();
           r=getr(i+2);
           next=ch(i+2,r);
           num.pop();
           now/=next;
           num.push(now);
       }
       else if(str[i]=='+')
       {
           op.push('+');
           r=getr(i+2);
           //printf("%d..\n",r);
           next=ch(i+2,r);
           num.push(next);
       }
       else if(str[i]=='-')
       {
           op.push('-');
           r=getr(i+2);
           next=ch(i+2,r);
           next*=-1;
           num.push(next);
       }
    }
    ans=0;
    while(!num.empty())
    {
        //printf("%d\n",num.top());
        ans+=num.top();
        num.pop();
    }
}

int  main()
{
    while(gets(str),strcmp(str,"0"))
    {
        fun();
        printf("%.2f\n",ans);
    }
    return 0;
}

 

posted @ 2015-07-26 23:14  sola94  阅读(104)  评论(0编辑  收藏  举报