hdu1237 简单计算器 (栈,代码比较繁琐,不过不难理解)

本人新手,代码比较笨,不过不难理解

#include<iostream>
#include<cstdio>
#include<stack>
using namespace std;
double pow(int a,double b){
    double res=b;
    for(int i=0;i<a;i++) res*=10;
    return res;
}
int main(){
    string s;
    while(getline(cin,s)){
        if(s=="0") break;
        s+="?";                                              //直接加一个没用的’?‘,后面就不用判断是否越界了
        int flag=0;double ans=0.0;
        stack<double> cal;
        for(int i=0;i<s.length();i++){           //从头开始读字符串
            if(s[i]==' ' || s[i]=='+') continue;    //如果是空格或加号直接跳过
            else if(s[i]>='0' && s[i]<='9'){     //遇到数字就判断有几位数
                double tmp=0.0;int wei=0;
                while(s[i]>='0' &&s[i]<='9'){  //如果前面没加'?',这里字符串末尾会越界,导致s[i]不存在
                    cal.push(s[i++]-'0');wei++;  //每个数字暂存到栈中,wei记录数字个数
                }
                for(int j=0;j<wei;j++) {tmp+=pow(j,cal.top()); cal.pop();} //取出栈顶元素wei次,用自己写的pow函数计算
                if(flag==0) cal.push(tmp);   //将最后计算结果压栈
                else {cal.push(-tmp);flag=0;}  //若flag为1代表该数为负数,将-tmp压栈,压栈后记得将flag=0
            }
            else if(s[i]=='-') {flag=1;}   //下一个数字是负数
            else if(s[i]=='*' || s[i]=='/') {  //如果是乘号或除号则跟加号一样往后找数字,然后再跟栈顶元素相乘/除
                char c=s[i];
                double tmp=0.0,top;int wei=0;

                i+=2;  //i+1是空格不用管
                while(s[i]>='0' &&s[i]<='9'){
                    cal.push(s[i++]-'0');wei++;
                }
                for(int j=0;j<wei;j++) {tmp+=pow(j,cal.top());cal.pop();}
                top=cal.top();cal.pop();
                if(c=='*'){top=top*tmp;cal.push(top);}
                else if(c=='/'){top=top/tmp;cal.push(top);}
            }
        }
        while(cal.size()) {ans+=cal.top();cal.pop();}  //最后将栈内所有元素相加即得答案
        printf("%.2lf\n",ans);
    }
    return 0;
}

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值