用 PHP 语言解决鸡兔同笼问题,设已知总头数为H,总脚数为Y,求鸡兔各有多少只?
<?php function fn($h,$y) { $maxC = $h; $minC = ceil($y/4); $c = $minC; $r = false; for(; $c<$maxC; $c++) { $r = $h - $c; if(($c*2 + $r*4) == $y) return $c; } return false; } $chick = fn(10,26); if(false == $chick){ echo "输入有误"; }else{ $rabbit = 10 - $chick; echo "鸡:{$chick},兔:{$rabbit}"; }
输出为:鸡:7,兔:3