rand函数
<stdlib.h>库函数 int rand(void) 返回一个范围在 0 到 RAND_MAX 之间的伪随机数。
RAND_MAX 是一个常量,它的默认值在不同的实现中会有所不同,但是值至少是 32767。
//rand()%100可以求出0-99的随机数
rand()%100+1
//就是0-100的随机数了
随机数种子
我们通过srand()函数来进行播种,根据当前时间生成随机数,保证生成数字的随机性.
void srand(unsigned int seed);
//我们通过当前时间,进行播种,生成的"种子"也就是随机的
//<time.h>头文件中的time()函数可以得当当前的时间
srand((unsigned)time(NULL));
时间戳
时间戳是指格林威治时间自1970年1月1日(00:00:00 GMT)至当前时间的总秒数。
生成随机数
生成三个随机数,进行一个测试
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
int a;
srand((unsigned)time(NULL));
a = rand() % 100 + 1;
printf("%d\n", a);
a = rand() % 10 + 1;
printf("%d\n", a);
a = rand() % 100 + 1;
printf("%d\n", a);
return 0;
}