下面的代码旨在生成区间[1unix time]中五个伪随机数的列表.我在default_random_engine
和time(0)
之间植入种子,这将在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分钟,再次try 发现第一个数字已经改变,现在总是生成26.它继续周期性地增加1,现在是32.它似乎与不断变化的值time(0)
相对应.
Why does the first number rarely change across runs, and then when it does, increment by 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;
}