系统生成一个随机数,利用二分法进行查找,并记录次数。代码及分析如下:
//生成随机数
Random rand = new Random();
int ans= rand.nextInt(100);
int begin=0,end=100,mid,count=0;
while (true){
//中间值用于表示猜的数
mid=(begin+end)/2;
//记录猜测的次数
count++;
System.out.println("第"+count+"次猜,猜的是:"+mid);
if (mid==ans){
System.out.println("用了"+count+"次猜对了");
System.out.println("正确答案是"+ans);
break;
}
if (mid<ans){
//如果猜的小的begin移动到mid前面一个,再继续猜
begin=mid+1;
continue;
}
if (mid>ans){
//如果猜的小的end移动到mid后面一个,再继续猜
end=mid-1;
continue;
}
}