系统生成一个随机数,利用二分法进行查找,并记录次数。代码及分析如下:
//生成随机数
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;
}
}
最后
以上就是英勇黑夜最近收集整理的关于使用二分查找猜数字的全部内容,更多相关使用二分查找猜数字内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复