【发布时间】:2016-04-12 07:11:22
【问题描述】:
我正在尝试使用以下代码用随机数填充我的数组
#include<iostream>
#include<random>
int main(){
int n = 5;
int list[10];
std::random_device rd;
std::mt19937 eng(rd());
std::uniform_int_distribution<> distr(0, 1000);
for(int i=0;i<n;i++)
list[i] = distr(eng);
std::cout<<"The list of elements is: ";
for(int i=0;i<n;i++)
std::cout<<list[i]<<" ";
}
对于 n = 5,我总是得到相同的输出
562 726 348 916 6
对于 n = 6,我总是得到相同的输出
562 726 348 916 6 594
这些数字不是随机的,我还检查了熵
std:cout<<rd.entropy();
这给了我输出
0
我做错了什么以及如何在我的数组中获取随机数?
【问题讨论】:
-
您可能希望包含您正在使用的编译器和版本以及您所在的平台。您的代码在 VS2013 中适用于我。
-
它也适用于 GCC 和 ArchLinux ...
-
你需要声明 srand(time(NULL))
-
@JarrodRoberson,那篇文章是关于
srand的,但这篇文章是关于random_device的。后者应该产生更好的随机性。