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

时间:2009-07-13 00:26:52

标签: 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();
}

我注意到每次运行程序时都会有相同的“随机”输出。所以我研究了随机数生成器并决定尝试种子,首先将它包含在randint()中。

    srand(5355);

一遍又一遍地生成相同的数字(我现在感觉很愚蠢。)

所以我认为我会聪明并实施这样的种子。

srand(rand());

这基本上和程序首先做的一样,但是输出了一组不同的数字(这是有意义的,因为rand()生成的第一个数字总是41。)

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

  1. 让用户输入一个数字并将其设置为种子(这很容易实现,但这是最后的手段) OR
  2. 不知何故将种子设置为计算机时钟或其他一些不断变化的数字。
  3. 我是否在头脑中,我现在应该停下来吗?选项2难以实施吗?还有其他想法吗?

    提前致谢。

5 个答案:

答案 0 :(得分:27)

选项2并不困难,你走了:

srand(time(NULL));

您需要为stdlib.h添加srand(),为time.h添加time()

答案 1 :(得分: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();
}

答案 2 :(得分:6)

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

函数srand(时间(NULL));

答案 3 :(得分:4)

问题在于,如果你没有为生成器播种,它将使用0播种自己(就像调用srand(0)一样)。 PRNG被设计为在播种时生成相同的序列(由于PNRG不是真正随机的,它们是确定性算法,可能有点因为它对测试非常有用)。

当您尝试使用随机数播种

srand(rand());

你实际上在做:

srand(0);
x = rand();   // x will always be the same.
srand(x);

作为FigBug mentioned,通常使用时间播种生成器。

答案 4 :(得分:0)

我认为这些文章的重点在于实现rand()中的算法而不是如何有效地播种它。

产生(伪)随机数是非常重要的,值得研究产生它们的不同技术。我不认为简单地使用rand()就是作者的想法。

相关问题