JS中while循环 ,二分法,产生随机数,计算机猜几次能猜中
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<script type="text/javascript">
var x=parseInt(Math.random()*10);
var low=0,high=9;
var count=0;
console.log(x);
while (low<=high){
count ++;
var mid=parseInt((low+high)/2);
console.log("第"+count+"次数猜"+mid);
if (x<mid) {
high=mid-1;
}
else if(x>mid){
low=mid+1;
}
else {
console.log("恭喜猜对了!");
break;
}
}
</script>
</body>
</html>