• 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
    ",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
    ",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..
    ",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
    ",num.top());
            ans+=num.top();
            num.pop();
        }
    }
    
    int  main()
    {
        while(gets(str),strcmp(str,"0"))
        {
            fun();
            printf("%.2f
    ",ans);
        }
        return 0;
    }
    
  • 相关阅读:
    理解HashSet及使用
    Java 集合类详解
    Java-泛型编程-使用通配符? extends 和 ? super
    回调函数及其用法
    log4j.properties 详解与配置步骤
    约瑟夫环
    泛型的约束与局限性
    把代码字体加大的办法
    System.arraycopy方法
    泛型数组列表与反射
  • 原文地址:https://www.cnblogs.com/sola1994/p/4678964.html
Copyright © 2020-2023  润新知