0

I'm using the rand function in my program in a for loop but it generates the same number all time.

for(a=0, a<10; a++){
  srand(3);
  int sleep = (rand() % 400) + 500;

}

It always generates 683 or something like that. What's the reason? How can I fix that?

Kraego
  • 2,978
  • 2
  • 22
  • 34

2 Answers2

3

Use the call of the function srand before the loop like for example

#include <stdlib.h>
#include <time.h>

//...

srand( ( unsigned int )time( NULL ) );

for(a=0, a<10; a++){
  int sleep = (rand() % 400) + 500;
  //...
}

Otherwise you will get the same values according to the call srand( 3 ); because "if srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated." (the C Standard, 7.22.2.2 The srand function).

Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

You are calling srand from inside of your loop. Each time you call it, you are setting the seed that is used to generate random numbers.

Move it outside of your loop as such:

srand(3);

for(a=0, a<10; a++){
  int sleep = (rand() % 400) + 500;
}

Additionally, each time you run your program, it will generate the same sequence of numbers. If you wish to avoid that, you'll need to pick a different seed for each run. Typically this is a number that changes each time, such as time of day in seconds or something more unique.

srand((unsigned int)time(NULL));
nullforce
  • 1,051
  • 1
  • 8
  • 13