-1

so I am trying to fill an array with random integers.

for (int i = 0; i < 2; i++){
    srand(time(NULL));
    array[i]=rand()%30; }`

Here is my code so far. I am currently getting the same random number twice. Would like to know if there is a way around this?

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
crooose
  • 111
  • 4
  • 10

2 Answers2

2

You seed the PRNG multiple times in the loop. It should be done only once.

By calling srand in the loop you reset the seed. And if you pass the same value to srand then the next call to rand will generate the exact same value.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621
1

rand() usually uses a PRNG, which uses the seed to generate the random number. srand ( time(NULL) ); is used to seed the pseudo-random number generator.

Currently, the time granularity of time() is 1 second, so if you seed the PNRG with the same value [time(NULL);] multiple time within the granularity period, call will to rand() generate the same random number.

Move the srand(time(NULL) outside the loop.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • 1
    Granularity of `time()` is unspecified by ISO/IEC 9899 (The C Programming Language). The granularity in seconds is a specification made by POSIX.1. – DevSolar Aug 28 '18 at 06:49