zoukankan      html  css  js  c++  java
  • 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;
    }
    
  • 相关阅读:
    单例模式的三种写法
    ASP.NET如何下载大文件
    字符串是引用类型
    SQL 事务隔离级别
    Sql Server 锁
    设非主键为聚集索引
    C#如何使用SqlCacheDependency
    简易系统后台架构
    matlab cross 3*1 向量叉乘
    Matlab求齐次方程的解
  • 原文地址:https://www.cnblogs.com/sola1994/p/4678964.html
Copyright © 2011-2022 走看看