随机数生成

随机数生成

在前一个例子(猜测数字)中,该数字每次都不同,这样更有趣。为此使用头文件 stdlib.h 中声明的函数 rand()。

int chosen = 0;
chosen = rand();

每次调用 rand 函数,它都会返回一个随机整数,这个值在 0 到 RAND_MAX 之间。由 rand 函数产生的整数称为伪随机数,因为真正的随机数只能在自然的过程中产生,而不能通过运算法则产生。

如果单纯使用 rand 没有设置种子,则每次都会产生一样的序列。

比如:

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

int main(void)
{
    int chosen = 0;
    for(int i = 0; i < 10; i++)
    {
        chosen = rand();
        printf("\n%d.",chosen);
    }

    return 0;
}Code language: PHP (php)

运行两次,都是得到下面的一组序列。

为了生成随机数,需要一个种子,并且每次种子都不一样。这时候使用另外一个库函数:<time.h> 头文件中声明的函数 time()。

time() 函数会把自 1970 年 1 月 1 号开始至今的总秒数返回为一个整数。因为时间永不停歇,所以每次执行程序都会得到不同的值。

time() 函数需要一个参数 NULL。NULL 是在 stdlib.h 中定义的符号,表示不引用任何内容。

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

int main(void)
{
    srand(time(NULL));
    int chosen = 0;
    for(int i = 0; i < 10; i++)
    {
        chosen = rand();
        printf("\n%d.",chosen);
    }

    return 0;
}Code language: PHP (php)

这样每次调用 rand 都会得到另外一个伪随机数。上限 RAND_MAX 相当大,如果需要更小范围,则可以使用取模的方式。

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

int main(void)
{
    srand(time(NULL));
    int chosen = 0;
    int limit = 20;
    for(int i = 0; i < 10; i++)
    {
        chosen = rand() % limit; //通过取模 获取从0到limit(不包括)之间的值
        printf("\n%d.",chosen);
    }

    return 0;
}Code language: PHP (php)

如果需要从 1 到 limit,则只需要加上 1 即可:

chosen = rand() % limit + 1;

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注