<? php
fwrite(STDOUT,"请输入0~999之间的任意数值: \n");
$num = trim(fgets(STDIN));
if($num > 999 || $num < 0 || !is_numeric($num)){
echo '请输入范围内数值哦!'."\n";
exit;
}
guess($num);
function guess($num){
$max = 999;
$min = 0;
$n = 0;
if($num == $max || $num == $min){
echo '我猜是: '.$num."\n";
echo '恭喜你,一次就猜对了!'."\n";
exit;
}
while($max > $min){
$middle = floor(($max+$min)/2);
echo '我猜是: '.$middle."\n";
if($middle - $num == 0){
echo '恭喜你,猜对了,您共猜了'.$n."次\n";
exit;
}else if($middle - $num > 0){
echo "猜高了,继续努力!\n";
$max = $middle;
}else if($middle - $num < 0){
echo "猜低了,继续努力!\n";
$min = $middle;
}
$n++;
}
}
?>