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;
    }
    
  • 相关阅读:
    iOS14
    iOS 音量键翻页实现
    pod 相关写法
    js 递归树结构数据查找指定元素的所有父级
    前端实现访问一个图片URL直接下载该图片
    HTML5 drag api 的使用
    vue 组件的 patch
    centos7安装nginx
    nginx常用配置说明
    遍历删除
  • 原文地址:https://www.cnblogs.com/sola1994/p/4678964.html
Copyright © 2011-2022 走看看