先调用rand() 让计算机跑出一个随机的数,一般最多猜7次就能猜中。 因为用二分法来取数, 2^6=64 2^7=128 最坏情况下执行7次就超过100,所以7次就够_
#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;
}
我没有严格按照二分法,(lll¬ω¬) 猜了8次才猜中…