每瓶啤酒2元,2个空酒瓶或4个瓶盖可换1瓶啤酒。10元最多可喝多少瓶啤酒? php

php中文网
发布: 2016-06-20 12:39:52
原创
1767人浏览过

//根据题意设定初始变量值//然后 一个while循环去操作//每换得一个瓶子,换的那个减去要做相应的数目//然后喝了啤酒后, 各数量加1//直到不符合要求。跳出循环 1 class beer{ 2  3     protected $uni_gai      = 4;    //每4个瓶盖1瓶 4     protected $uni_bottle   = 2;    //每两个瓶子换1瓶 5     protected $uni_beer     = 2;    //每瓶2块钱 6     protected $rs           = array();//存取结果 7     protected $total        = 0;      //当前买了啤酒的数量 8     protected $gai          = 0;      //当前有多少个啤酒 9     protected $empty_bottle = 0;      //空瓶子10 11     public function __construct($money){12         $cur = $money / $this->uni_beer;13         $this->total        = $cur;14         $this->gai          = $cur;15         $this->empty_bottle = $cur;16     }17 18     public function run(){19         while($this->gai > 0 || $this->empty_bottle > 0){20             if($this->gai >= $this->uni_gai){21                 $this->deal_num('gai');22             }23             if($this->empty_bottle >= $this->uni_bottle){24                 $this->deal_num('empty_bottle');25             }26 27             $this->check_overflow();28         }29         return $this->rs;30     }31 32     public function deal_num($type){33         if($type == 'gai'){34             $this->gai -= $this->uni_gai;35         }else{36             $this->empty_bottle -= $this->uni_bottle;37         }38         $this->gai++;39         $this->empty_bottle++;40         $this->total++;41     }42     public function check_overflow(){43         if($this->gai < $this->uni_gai && $this->empty_bottle < $this->uni_bottle){44             $this->rs['gai']          = $this->gai;45             $this->rs['total']        = $this->total;46             $this->rs['empty_bottle'] = $this->empty_bottle;47             $this->gai                = 0;48             $this->empty_bottle       = 0;49         }50     }51     public function _print(){52         echo 'gai:', $this->gai;53         echo '<br>';54         echo 'empty_bottle:', $this->empty_bottle;55         echo '<br>';56         echo 'total', $this->total;57         echo '<hr>';58     }59 }60 61 $peer = new beer(10);62 $rs   = $peer->run();63 print_r($rs);
登录后复制

打印的结果是: array ( [gai] => 3 [empty_bottle] => 1 [total] => 15 )

盖子 3个, 空瓶子 1个, 总共喝了15瓶啤酒

PHP速学教程(入门到精通)
PHP速学教程(入门到精通)

PHP怎么学习?PHP怎么入门?PHP在哪学?PHP怎么学才快?不用担心,这里为大家提供了PHP速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:php中文网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号