【发布时间】:2013-07-11 16:18:33
【问题描述】:
这与这个问题有关 - random number generation in C++ ... first number not very random
#include <iostream>
#include <stdlib.h>
#include <time.h>
using namespace std;
int main()
{
srand((unsigned int)time(NULL));
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
cout << rand() / double(RAND_MAX) << endl;
return 0;
}
如果您一遍又一遍地运行二进制文件 (.exe),您会注意到第一个结果始终具有相同的前三个数字。例如。每次运行总是 0.54xxxx。
不,这不是因为我发现了不存在的模式。每次运行之间等待几秒钟也无济于事。
编辑:只有第一个结果具有前三个相同的数字。其余的是“随机查找”。此外,生成器以 srand() 为种子(在上面代码示例的第一行)。
【问题讨论】:
-
你用的是什么编译器?
-
GNU GCC 编译器(在代码块 12.11 中)。
-
版本?无法使用 gcc 4.6.3 重现它。我在 MS vc 上看到过类似的东西,从来没有在 gcc 上看到过。请参阅:stackoverflow.com/questions/17385541/c-predictable-rand-output
-
@simonc - 前三个数字对于每次运行的第一个结果都是相同的。例如0.54xxxx.
-
@KarolyHorvath - 版本 4.7.1