问题描述
我正在尝试使用下面的代码用随机数填充数组
I am trying to fill my array with random numbers using the following piece of code
#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,我总是得到相同的输出
For n = 5, I always get the same output
562 726 348 916 6
对于n = 6,我总是得到相同的输出
For n = 6, I always get the same output
562 726 348 916 6 594
这些数字是随机的,我还检查了熵
These numbers arent random, I also checked the entropy
std:cout<<rd.entropy();
这给了我输出
0
我做错了什么,如何在数组中获得随机数?
What am I doing wrong and how do I get random numbers in my array?
推荐答案
调用 std :: random_device
上的"> entropy()
成员函数,以了解您的实现是否正确实现:
Call the entropy()
member function on std::random_device
to find out whether your implementation implements it properly:
(源)
如果是这种情况,请调用 entropy()
将返回 0
:
If this is the case, a call to entropy()
will return 0
:
在这种情况下,您需要使用其他回退机制进行播种.例如,您可以像以前的C天一样使用基于时间的种子.
If that is the case, you need to use a different fallback mechanism for seeding. For instance, you could use a time-based seed like in the old C-days.
尤其是在台式机平台上,您应该希望将 std :: random_device
实施为适当的不确定源.如果不是这种情况,则您可能只是在使用标准库实现的旧版本.如果您认为该实现应支持不确定的 std :: random_device
,但不支持,请考虑向您的标准库维护者提交错误报告.
On desktop platforms in particular, you should expect std::random_device
to be implemented as a proper non-deterministic source though. If this is not the case, you might just be using a very old version of the standard library implementation. If you have the feeling that the implementation should support non-deterministic std::random_device
but it does not, consider filing a bug report with your standard library maintainer.
这篇关于随机数生成器始终生成相同的数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!