This question already has an answer here:
So I'm practicing classes and headers. I'm trying to create a simpler random number generator by putting it into another class. The source code compiles without any errors. However, as you can see in the source code I use time(0) as a seed to generate random numbers. Yet somehow the seed doesn't change when I restart the program multiple times to test the randomness. The seed is apparently the same. Why is this ?
main.cpp
#include <iostream>
#include "RandomNumber.h"
using namespace std;
int main(){
RandomNumber rand;
int a = 10000;
int randomnumber = rand.RandNumGen(1, 100);
cout << "10 000 - a random number between 1 and 100 looks like this\n" << a << " - " << randomnumber << " = " << a - randomnumber << endl;
return 0;
}
RandomNumber.h
#include <iostream>
#include <ctime>
#include <random>
using namespace std;
class RandomNumber
{
public:
RandomNumber();
int RandNumGen(int minimum, int maximum);
protected:
private:
};
#endif
RandomNumber.cpp
#include "RandomNumber.h"
using namespace std;
RandomNumber::RandomNumber(){
}
int RandomNumber::RandNumGen(int minimum, int maximum){
default_random_engine generator(time(0));
uniform_int_distribution<int> RNG(minimum, maximum);
return RNG(generator);
}
In short. The RandNumGen function in the RandomNumber class returns the same random number even though the seed is constantly changing (using time in seconds).
Aucun commentaire:
Enregistrer un commentaire