注册 登录
考研论坛 返回首页

sleeping1346的个人空间 http://home.kaoyan.com/?2907038 [收藏] [复制] [分享] [RSS]

日志

hdu1237------简单计算器

已有 1761 次阅读2011-3-12 22:14 |个人分类:ACM摸索|

有个地方要注意,就是读取过程中计算完某一轮后,应该检查能否继续计算,否则会出错

#include<stdio.h>
#include<string>

bool cmp(char a,char b)
{
     if(a=='*'||a=='/')return true;
     if(b=='*'||b=='/')return false;
     else return true;
}

double cpt(double a,double b,char o)
{
    if(o=='+')return a+b;
    if(o=='-')return a-b;
    if(o=='*')return a*b;
    return a/b;
}

int main()
{
    char s[800],op[101],o,c;
    double num[101],n1,n2;
    int o_top,n_top;
    int i,temp,l;
    while(gets(s)&&strcmp(s,"0")!=0)
    {
        l=strlen(s);o_top=n_top=0;
        for(temp=i=0;i<=l;i++)
        {
           if(s[i]>='0'&&s[i]<='9')temp=temp*10+s[i]-'0';
           else if(s[i]!=' ')
           {
                num[n_top++]=temp;
                temp=0;
                if(s[i]!='\0')//+ - * /
                {
                   if(o_top==0||!cmp(op[o_top-1],s[i]))op[o_top++]=s[i];
                   else if(cmp(op[o_top-1],s[i]))
                   {
                        n2=num[--n_top];n1=num[--n_top];
                        o=op[--o_top];
                        num[n_top++]=cpt(n1,n2,o);
                        op[o_top++]=s[i];
                        while(o_top>1&&cmp(op[o_top-2],op[o_top-1]))
                        {
                            n2=num[--n_top];n1=num[--n_top];
                            c=op[--o_top];
                            o=op[--o_top];
                            num[n_top++]=cpt(n1,n2,o);
                            op[o_top++]=c;
                         }
                   }
                }
           }
         }  
         while(o_top>0)
         {
             n2=num[--n_top];n1=num[--n_top];
             o=op[--o_top];
             num[n_top++]=cpt(n1,n2,o);
         }
         printf("%.2lf\n",num[n_top-1]);
    }
    return 0;
}


路过

雷人

握手

鲜花

鸡蛋
收藏 分享邀请 分享到人人 举报

评论 (0 个评论)

关于我们|商务合作|小黑屋|手机版|联系我们|服务条款|隐私保护|帮学堂| 网站地图|院校地图|漏洞提交|考研帮

GMT+8, 2024-5-6 23:56 , Processed in 0.051007 second(s), Total 8, Slave 8(Usage:3M, Links:[2]1,1_1) queries , Memcache On.

Powered by Discuz!

© 2001-2017 考研 Inc.

返回顶部
× 关闭