简体   繁体   中英

Random Number Generator C++ Error in CMD

I'm trying to make a random number generator, to generate a number between 0 and 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.

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.

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.

std::random_device doesn't actually need to be implemented.

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.

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 . You can change your function to void if you do not want to return anything.

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

Throws: A value of an implementation-defined type derived from exception if the random_device could not be initialized.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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