Random Number Generator - rand() & srand()

I'm trying to use rand() to produce a random number, however, the result of this function is the same everytime I run the program...here is my code...simple:

1
2
	UINT RNDCARD(void){srand ( timeGetTime() ); return (UINT)rand() % 13 + 1;}
	UINT RNDSUIT(void){srand ( timeGetTime() ); return (UINT)rand() % 3 + 0;}

it is implemented with the following code:
1
2
3
4
5
6
7
8
9
while(chkInPlay)
	{	
		BOOL inPlay = false;
		UINT c = RNDCARD();
		assert(c >= 1 && c <= 13);
		UINT s = RNDSUIT();
		assert(s >= 0 && s <= 3);
...
}


How do I correctly use rand()?
I think it is due to that the returned value of timeGetTime() is the same.

You should use srand only once in the very begining.
the problem was that I needed to get a new set of random numbers when "the game is reset" not only when the "program restarts." i added an srand() call when the program is reset instead of when RNDCRD() and RNDSUIT() are called...it seems to work. just not sure why...what does srand() do exactly?
Last edited on
It'll pass a seed value into the pseudo-random number generator.

That value will be used when generating numbers, so it needs to be something relatively distinctive, which is why we use the system time.

As vlad pointed out, srand should really only be called once in your program.
srand() seeds the PRNG, you just call it once at the beginning of you program. rand() returns the next number in the sequence.
Topic archived. No new replies allowed.