下面的代码旨在生成区间 [1,100] 中的五个伪随机数的列表。我播种default_random_engine
with time(0)
,它返回系统时间UNIX时间 https://en.wikipedia.org/wiki/Unix_time。当我使用 Microsoft Visual Studio 2013 在 Windows 7 上编译并运行该程序时,它按预期工作(见下文)。然而,当我在 Arch Linux 中使用 g++ 编译器执行此操作时,它的行为很奇怪。
在Linux中,每次会生成5个数字。每次执行时最后 4 个数字都会不同(通常是这种情况),但第一个数字将保持不变。
Windows 和 Linux 上 5 次执行的输出示例:
| Windows: | Linux:
---------------------------------------
Run 1 | 54,01,91,73,68 | 25,38,40,42,21
Run 2 | 46,24,16,93,82 | 25,78,66,80,81
Run 3 | 86,36,33,63,05 | 25,17,93,17,40
Run 4 | 75,79,66,23,84 | 25,70,95,01,54
Run 5 | 64,36,32,44,85 | 25,09,22,38,13
更神秘的是,第一个数字在 Linux 上会定期递增 1。获得上述输出后,我等了大约30分钟,再次尝试发现第一个数字已经改变,现在总是生成为26。它继续周期性地增加1,现在为32。它似乎对应随着价值的变化time(0)
.
为什么第一个数字在运行过程中很少发生变化,而当变化时,则增加 1?
代码。它整齐地打印出 5 个数字和系统时间:
#include <iostream>
#include <random>
#include <time.h>
using namespace std;
int main()
{
const int upper_bound = 100;
const int lower_bound = 1;
time_t system_time = time(0);
default_random_engine e(system_time);
uniform_int_distribution<int> u(lower_bound, upper_bound);
cout << '#' << '\t' << "system time" << endl
<< "-------------------" << endl;
for (int counter = 1; counter <= 5; counter++)
{
int secret = u(e);
cout << secret << '\t' << system_time << endl;
}
system("pause");
return 0;
}