2

I am calling to a random number generator function twice and theoretically should be getting 2 random numbers each time but instead I am being given the same number both times.

I have tried calling to the function in different way and replaced the integer in srand to 0 and null but still receive the same answer

 int randomNUM()
 {
    srand(time(NULL));
    int RL = rand() % 100;
    return RL;
    RL = 0;
 }

 int main()
 {
     int RL = randomNUM();
     int RL2 = randomNUM();

     cout << "RL: " << RL << endl;
     cout << "RL2: " <<RL2 << endl;

 }

I expect the results for RL and RL2 to be completely randomized numbers between 1-99 but instead get the same number for each of them.

  • 2
    srand is guarantied to return the same number with the same seed. The likes of[this](https://stackoverflow.com/questions/3032726/rand-generating-the-same-number-even-with-srandtimenull-in-my-main) – lakeweb Apr 23 '19 at 01:16

3 Answers3

3

You should only call srand() once, right at the beginning of your program. Once you call srand() the string of random numbers is reset.

Do something like

 int randomNUM()
 {
    int RL = rand() % 100;
    return RL;
    RL = 0;
 }

 int main()
 {
     srand(time(NULL));
     int RL = randomNUM();
     int RL2 = randomNUM();

     cout << "RL: " << RL << endl;
     cout << "RL2: " <<RL2 << endl;

 }
rtpax
  • 1,687
  • 1
  • 18
  • 32
1

srand sets the seed. You should do it once in main, not every time you want a random number. So instead, you should have

 int randomNUM()
 {
    // removed srand(time(NULL));
    int RL = rand() % 100;
    return RL;
    RL = 0;
 }

 int main()
 {
     srand(time(NULL));
     int RL = randomNUM();
     int RL2 = randomNUM();

     cout << "RL: " << RL << endl;
     cout << "RL2: " <<RL2 << endl;

 }
davidlowryduda
  • 2,404
  • 1
  • 25
  • 29
1

You are reseeding the random number generator each time you call randomNUM(). Since it doesn't take much time between calls to randomNUM(), then the value that time() returns is the same both times. As a result, the random number generator restarts the random number sequence at the same beginning point. There are two ways you can solve the problem:

  1. Move the call to srand() to be before all calls to randomNUM()
  2. Have a static boolean value that you initialize to false and then set to true the first time you call srand(). You can then check what the value of this variable is to determine whether you should call srand().
Jonathan Geisler
  • 430
  • 3
  • 14