码迷,mamicode.com
首页 > 其他好文 > 详细

HDU 1237 简单计算器 (栈 )

时间:2015-07-27 00:16:04      阅读:138      评论:0      收藏:0      [点我收藏+]

标签:

 

 

#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;
}

 

HDU 1237 简单计算器 (栈 )

标签:

原文地址:http://www.cnblogs.com/sola1994/p/4678964.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!