Realize the guessing game with C language
Assuming a number from 1 to 100, please design the program so that the user can guess the correct number after a limited number of steps.
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
int main() {
srand(time(0));
int number = rand() % 100 + 1;
int count = 0;
int a = 0;
printf("我已经想好了一个1到100之间的数。");
do {
printf("猜猜这个1到100之间的数:");
scanf("%d",&a);
count++;
if (a > number) {
printf("你猜的这个数大了");
}
else if (a < number) {
printf("你猜的这个数小了");
}
} while (a != number);
printf("太好了,你用了%d次就猜到了答案。\n",count);
return 0;
}
For numbers between 1 and 100, you can get the correct number up to 7 times, and you only need to halve each time.
用二分法查找具有很高的效率(这里我们统一向下取整)。
如:假设随机数是15,那么可以先取50,会显示大了;
用二分查找,我们可以取(0+50/2)取25,此时会显示大了;
然后我们可以取(0+25/2)取12;
此时显示小了;然后我们取(12+25)/2 取18;
此时显示大了,我们再取(12+18)/2取15;
此时恰好与要猜的数15一致,共用5次就猜到正确答案,实际上当用户好运到爆棚时,1次就可能猜对,就算再背,只要正确运用二分法查找,最多花费7次就能找到正确的数。