-1
int random(){//function for random number generation
time_t t;
srand((unsigned) time(&t));
int rand = rand()%468;
return rand;
}

I want to put this function in a loop so it assigns a random number to a variable during each iteration of the loop, so i figured i would try this:

for(x=0;x<n;x++){
y=random();
printf("%d\n",y);
}

However this doesn't work as i expected, y just gets the number from the first iteration and repeats it, can someone explain how i can force the function to recall so it will set a new value to y?

Blaze Blue
  • 15
  • 1
  • 3

1 Answers1

7

You should not call srand() everytime before calling rand().

The way you are calling srand() always passes the same value as the seed, because the difference in seconds between each call is 0, since it's a lot smaller than 1s.

Since you always call srand() with the same seed and right before rand(), you will get always the same value from rand().

Just call srand() once at the start of the program, so in every run there will be different random numbers generated.

Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97