HellfireXP wrote: |
---|
Move your srand(time(0)); outside your function and before your loop execution. It only needs to be called once at the beginning of your program, otherwise because you're calling it so fast within a loop, it will actually give you the same value every time. |
Halfway right. srand is best placed as the very first line in main, always (there is other reasons for it, but for most applications, follow that).
What does srand do? It "seeds" the rand function. rand() doesn't actually return a random value, honestly, it just seems that way. Depending on the seed, we'll get to that later, the computer gives us a number. There is a huge line of numbers somewhere telling the computer what number should be returned (obviously it doesn't work like that, but for all practical sense of it, let's pretend it does). Each time you call
rand()
, it reads the next number on that list.
What is a seed? A seed is, going off of the number lists I used as an example earlier, essentially the list number to use. srand accepts any unsigned int, positive number or zero. So we can write
srand(5342);
and every time we run the program, we will get the same exact numbers. That does us no good (it's not random enough). So instead, we pass it the return value of
time(0)
. The function time, using 0 as a parameter, will return the number of seconds that have elapsed since January 1st, 1970. This is great since it's very unlikely that someone is going to be running the program twice in less than a second. Every second = a new seed.
So, if you're constantly calling srand then rand, you're reseeding the random numbers with the same one you just had. Now is the stuff I'm unsure of, I don't remember if time() returns the number of seconds based off of the current system time, or if it's based off of when the program was launched. Either way, srand once, and only once.
I hope this enlightened you in someway.