如何让电脑较为快的,不重复的猜到1-100直接的一个随机数。 io
以c语言为例,例如在猜1-100的数字时,假如,随机产生一个数字number=rand()%100+1,那么若是随机猜的第一个数字大于了number,咱们就把这个数存到end里面,若是随机猜的第二个数字小于了number,咱们就把这个数字存到first里面,那么问题就是接下来产生的随机数要在介于first和end之间的一个随机数,则,用rand()%(end-first)+first能够获得这个随机数。 随机数
如下为示例代码:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int func(int first,int end)
{
return rand()%(end-first) +first+1;
}
int main(void)
{
srand(time(NULL));
int num_1=rand()%100+1;
//int num_2;
int count=0;
int first=0;
int end=100;
printf("须要猜的数字为:%d\n",num_1);
while(1)
{
printf("请你猜一个数:\n");
int num_2=func(first,end);
printf("%d",num_2);
if(num_2>num_1)
{
printf("你输入的数大了!\n");
end=num_2;
count++;
}
else if(num_2<num_1)
{
printf("你输入的数小了!\n");
first=num_2;
count++;
}
else
{
printf("恭喜你答对了哦!\n");break;
}
}
printf("你一共用了%d次哦",count);
return 0;
} im