一、函数
1.rand()函数
2.srand()函数
3.time()函数
包含在time.h。
1.rand
magic=rand()%100+1;
如果直接这样用答案一直是42。
--------------------------------------
int i;
for(i=0;i<10;i++)
{
printf("%d\n",rand()%100+1);
}
这样输出的结果是
2.srand
输入seed(种子)产生随机数。
srand(seed)
unsigned int seed;
int magic;
scanf("%u",&seed);
srand(seed);
magic=rand()%100+1;
printf("%d",magic);
根据输入的seed不同 ,产生的数也不同。
固定的seed产生固定的值。2->46。3->49。
int i,j;
for(i=1;i<=10;i++)
{
srand(i);
for(j=1;j<=10;j++)
{
printf("%d\t",rand());
}
printf("\n");
}
这样i不同产生的随机数也不一样。
ps:\t是一个Tab。
3.time()
#include <time.h>
srand(time(NULL));
time作为seed。
可以根据时间来产生随机数。就是系统时间作为seed。
二、
printf("Please enter seed:");
scanf("%u",&seed);
srand(seed);
在输入过程中可以自己输入seed。固定的数字对应固定的数。但是作为猜数游戏不太好。会被记住。