在C++中使用rand()函数的正确方法是什么?

tri*_*ker 7 c++ random

我正在做一本书练习,写一个生成伪随机数的程序.我开始简单了.

#include "std_lib_facilities.h"

int randint()
{
    int random = 0;
    random = rand();
    return random;
}

int main()
{
    char input = 0;
    cout << "Press any character and enter to generate a random number." << endl;
    while (cin >> input)
    cout << randint() << endl;
    keep_window_open();
}
Run Code Online (Sandbox Code Playgroud)

我注意到每次运行程序时都会有相同的"随机"输出.所以我调查了随机数生成器并决定尝试播种,首先在randint()中包含它.

    srand(5355);
Run Code Online (Sandbox Code Playgroud)

这只是反复生成相同的数字(我现在感觉很愚蠢.)

所以我认为我会聪明并实现这样的种子.

srand(rand());
Run Code Online (Sandbox Code Playgroud)

这基本上只是与程序在第一时间做的相同,但输出了一组不同的数字(这是有道理的,因为rand()生成的第一个数字总是41.)

我能想到的唯一让它更随机的是:

  1. 让用户输入一个数字并将其设置为种子(这很容易实现,但这是最后的手段)或者
  2. 不知何故将种子设置为计算机时钟或其他一些不断变化的数字.

我是否在我脑海中,我现在应该停下来吗?选项2难以实施吗?还有其他想法吗?

提前致谢.

Joh*_*n T 28

选项2并不难,在这里你去:

srand(time(NULL));
Run Code Online (Sandbox Code Playgroud)

你需要包含stdlib.hfor srand()time.hfor time().

  • 另外,在main附近调用srand(),因为你应该只调用一次.每次生成新号码时都不要打电话. (2认同)

Mar*_*ork 8

srand()应该只使用一次:

int randint()
{
    int random = rand();
    return random;
}

int main()
{
    // To get a unique sequence the random number generator should only be
    // seeded once during the life of the application.
    // As long as you don't try and start the application mulitple times a second
    // you can use time() to get a ever changing seed point that only repeats every
    // 60 or so years (assuming 32 bit clock).
    srand(time(NULL));
    // Comment the above line out if you need to debug with deterministic behavior.

    char input = 0;
    cout << "Press any character and enter to generate a random number." << endl;

    while (cin >> input)
    {
        cout << randint() << endl;
    }
    keep_window_open();
}
Run Code Online (Sandbox Code Playgroud)


Rol*_*ien 6

通常使用当前时间为随机数生成器播种.尝试:

函数srand(时间(NULL));