简体   繁体   English

CMD中的随机数生成器C ++错误

[英]Random Number Generator C++ Error in CMD

I'm trying to make a random number generator, to generate a number between 0 and 999. 我正在尝试制作一个随机数生成器,以生成0到999之间的数字。

I did originally have it running where the seed for mt19937 was generated from time(null), but found that this would cause the number to change once per second, and was not fast enough for when I called it again from within the for loop. 我最初确实在从time(null)生成mt19937的种子的位置运行它,但是发现这将导致该数字每秒更改一次,并且速度不足以使我在for循环中再次调用它。

I'm using code::blocks to compile my code, and it compiles with no errors, but when I run the code I an error in cmd. 我正在使用code :: blocks编译我的代码,并且编译没有错误,但是当我运行代码时,我在cmd中出错。

Error: terminate called after throwing an instance of 'std::runtime_error'
  what():  random_device::random_device(const std::string&)

Am I doing something horribly wrong? 我做错什么了吗?

#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;
}

UPDATE: 更新:

I've now run the exact same code from Visual Studio, and there is no error. 我现在已经从Visual Studio运行了完全相同的代码,并且没有错误。

std::random_device doesn't actually need to be implemented. std::random_device实际上并不需要实现。

http://www.cplusplus.com/reference/random/random_device/ http://www.cplusplus.com/reference/random/random_device/

3rd paragraph. 第三段。 If the device is no good, they throw an exception. 如果设备不好,则抛出异常。 Try using a different seeded RNG. 尝试使用其他种子RNG。

Your function never returns a value. 您的函数从不返回值。 Since you have an int return type your function must return an something that is convertible to an int . 由于您具有int返回类型,因此您的函数必须返回可转换为int You can change your function to void if you do not want to return anything. 如果不想返回任何内容,可以将函数更改为void

Since your exception is referencing the constructor name then it appears the random device could not be created. 由于您的异常引用了构造函数名称,因此似乎无法创建随机设备。 The C++14 standard 26.5.6.4 has C ++ 14标准26.5.6.4具有

Throws: A value of an implementation-defined type derived from exception if the random_device could not be initialized. 抛出:如果random_device无法初始化,则从异常派生的实现定义类型的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM