所需要的头文件:

#include <stdlib.h>
#include <time.h>

一、int rand(void) 函数

C 库函数 int rand(void) 返回一个范围在 0 到 RAND_MAX 之间的伪随机数。

RAND_MAX 是一个常量,它的默认值在不同的实现中会有所不同,但是值至少是 32767。\

示例代码:

#include <stdio.h>#include <stdlib.h>int main(){int a = rand();printf("%d\n",a);return 0;    }

运行结果:

随机数的本质:

多次运行上面的代码,你会发现每次产生的随机数都一样,这是怎么回事呢?为什么随机数并不随机呢?
实际上,rand() 函数产生的随机数是伪随机数,是根据一个数值按照某个公式推算出来的,这个数值我们称之为“种子”。种子和随机数之间的关系是一种正态分布。

种子在每次启动计算机时是随机的,但是一旦计算机启动以后它就不再变化了;也就是说,每次启动计算机以后,种子就是定值了,所以根据公式推算出来的结果(也就是生成的随机数)就是固定的。

二、void srand(unsigned int seed) 函数

函数说明:seed -- 这是一个整型值,用于伪随机数生成算法播种;同时,该函数不返回任何值!

在实际开发中,我们可以用时间作为参数,只要每次播种的时间不同,那么生成的种子就不同,最终的随机数也就不同。

C 库函数 void srand(unsigned int seed) 播种,然后通过函数 rand()生成随机数。

使用 <time.h> 头文件中的 time() 函数即可得到当前的时间(精确到秒),就像下面这样:

方式1:

srand(time(NULL));

方式2:

time_t t;srand((unsigned) time(&t));

示例代码:

#include <stdio.h>#include <stdlib.h>#include <time.h>void test_rand(void)    {unsigned long n;srand((unsigned)time(NULL));for(int i = 0; i < 100; i++)    {        n = rand();printf("%d\n", n);    }}int main(){test_rand();return 0;}

运行结果:

三、time()函数

函数原型: time_t time(time_t *timer)

参数说明: timer=NULL时得到当前日历时间(从1970-01-01 00:00:00到现在的秒数),timer=时间数值时,用于设置日历时间,time_t是一个unsigned long类型。如果 timer不为空,则返回值也存储在变量 timer中。

函数功能: 得到当前日历时间或者设置日历时间

函数返回: 当前日历时间

四、如何生成指定范围的随机数

在实际开发中,我们往往需要一定范围内的随机数,过大或者过小都不符合要求,那么,如何产生一定范围的随机数呢?我们可以利用取模的方法:

int a = rand() % 10;    //产生0~9的随机数,注意10会被整除

如果要规定上下限:

int a = rand() % 51 + 13;    //产生13~63的随机数

分析:取模即取余,rand()%51+13我们可以看成两部分:rand()%51是产生 0~50 的随机数,后面 +13保证 a 最小只能是 13,最大就是 50+13=63。

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main() {
    // 使用当前时间作为随机数种子
    srand(time(NULL));

    // 生成一个随机数
    int random_number = rand();

    // 输出随机数
    printf("随机数: %d\n", random_number);

    // 生成一个范围在 [0, 99] 的随机数
    int random_in_range = rand() % 100;
    printf("范围在 [0, 99] 的随机数: %d\n", random_in_range);

    return 0;
}