我正在尝试制作一个随机数生成器,生成一个介于0和999之间的数字。
我最初确实让它在mt19937的种子从time(null)生成的地方运行,但发现这会导致数字每秒更改一次,并且当我在for循环中再次调用它时速度不够快。
我使用code::块来编译我的代码,它编译没有错误,但是当我运行代码时,我在cmd中出现错误。
Error: terminate called after throwing an instance of 'std::runtime_error'
what(): random_device::random_device(const std::string&)
我做了什么可怕的错误吗?
#include <iostream>
#include <random>
using namespace std;
//Random Number Generator
int numGen() {
//Random Number Generator
random_device rd;
mt19937 mt(rd());
uniform_int_distribution<int> dist(0, 999);
for (int I = 0; I < 6; i++) {
cout <<dist(mt) << " ";
}
cout <<endl;
}
更新:我现在已经在Visual Studio中运行了完全相同的代码,并且没有错误。
std::random_device
实际上不需要实现。
第三段。如果设备不好,他们会抛出异常。尝试使用不同的种子RNG
你的函数从不返回值。因为你有一个int
返回类型,你的函数必须返回一个可以转换为int
的东西。如果您不想返回任何东西,可以将函数更改为void
。
因为你的异常引用了构造函数的名字,所以看起来随机设备不能被创建。c++ 14标准26.5.6.4有
抛出:一个实现定义类型的值,该值派生自random_device无法初始化。