Generating Random Numbers with loop

closed account (NCRLwA7f)
Hello and happy thanksgiving to all. I was just sitting here playing around with a loop to generate random numbers and I remembered that I had a question about the process that I have been forgetting to get some input on.

say I generate a random number between 1 - 100 with the following function
1
2
3
4
5
6
7
8
9
10
11

int RandVal()
{
  srand(time(NULL));

  int value;

  value = rand() % 100 + 1;

return value;
}


Then say I stick this into a loop
1
2
3

for(int ndx = 0; ndx < 30; ndx++)
   RandVal();


my output will be something like this

47
47
47
47
47
....... so on so on for 30 values.

yet if I run the loop again I will get a different random value.
Is it because the loop is running really fast that the time "seed" does not have enough time to change to generate a different value for each output? if so, is there a way to slow the loop to give the time a chance to catch up?

ok well thank you for your time.
Last edited on
Do not call srand() multiple times. srand() sets the RNG to a particular starting point. Calling srand() repeatedly can cause the RNG to return the same random numbers. srand() should be called ONCE at the beginning of main().
http://www.cplusplus.com/reference/cstdlib/srand/
closed account (NCRLwA7f)
Ok, this makes sense, the link provides a good explanation. I moved srand(time()); outside the function to the beginning of main and it has solved my problem. I really had not noticed this in past projects.
Topic archived. No new replies allowed.