二分法猜数
两个人A和B猜数,先输入一个n(1<=n<=1000),A从1到n之间选一个数,B来猜这个数,A会告诉B是大了还是小了,B至少要多少次才能确定A选的那个数呢
#include<stdio.h>
int main(){
int n,a;
printf("请输入游戏范围:\n");
scanf("%d",&n);
printf("请输入游戏数字:\n");
scanf("%d",&a);
int count=1;
int low=1,high=n;
int tmp=(low+high)/2;
while(tmp!=a){
if(a<tmp){
high=tmp-1;
}
else{
low=tmp+1;
}
tmp=(low+high)/2;
count++;
}
printf("至少需要%d次才能猜到数字",count);
return 0;
}
420

被折叠的 条评论
为什么被折叠?



