//根据题意设定初始变量值
//然后 一个while循环去操作
//每换得一个瓶子,换的那个减去要做相应的数目
//然后喝了啤酒后, 各数量加1
//直到不符合要求。跳出循环
1 class Beer{ protected $uni_gai = 4; //每4个瓶盖1瓶
protected $uni_bottle = 2; //每两个瓶子换1瓶
protected $uni_beer = 2; //每瓶2块钱
protected $rs = array();//存取结果
protected $total = 0; //当前买了啤酒的数量
protected $gai = 0; //当前有多少个啤酒
protected $empty_bottle = 0; //空瓶子 public function __construct($money){
$cur = $money / $this->uni_beer;
$this->total = $cur;
$this->gai = $cur;
$this->empty_bottle = $cur;
} public function run(){
while($this->gai > 0 || $this->empty_bottle > 0){
if($this->gai >= $this->uni_gai){
$this->deal_num('gai');
}
if($this->empty_bottle >= $this->uni_bottle){
$this->deal_num('empty_bottle');
} $this->check_overflow();
}
return $this->rs;
} public function deal_num($type){
if($type == 'gai'){
$this->gai -= $this->uni_gai;
}else{
$this->empty_bottle -= $this->uni_bottle;
}
$this->gai++;
$this->empty_bottle++;
$this->total++;
}
public function check_overflow(){
if($this->gai < $this->uni_gai && $this->empty_bottle < $this->uni_bottle){
$this->rs['gai'] = $this->gai;
$this->rs['total'] = $this->total;
$this->rs['empty_bottle'] = $this->empty_bottle;
$this->gai = 0;
$this->empty_bottle = 0;
}
}
public function _print(){
echo 'gai:', $this->gai;
echo '<br>';
echo 'empty_bottle:', $this->empty_bottle;
echo '<br>';
echo 'total', $this->total;
echo '<hr>';
}
} $peer = new Beer(10);
$rs = $peer->run();
print_r($rs);

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

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

04-29 22:03