Skip to main content
GameDev.net gamedev.net
🔒 Locked

Rand() question

Started by raptorstrike Nov 14, 2004 at 3:50 PM 8 replies 1.2k views
Original Post
raptorstrike
raptorstrike
ok i feel stupid asking this but im calling srand(3); X=rand()%3; and i get the same think everytime why?
____"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
KrazeIke
KrazeIke
If you use the same seed every time, you will get the same result. Usually people pass the current time to srand.
nmi
nmi
That's correct.

srand() initialises your random number generator to a specific seed. So subsequent calls to rand() will always return the same sequence of numbers when the same seed was used.

You can feed the current time or some other really random value to srand() to have a unique chain of random numbers.
raptorstrike
raptorstrike
i need a number 0-2 as a rand # when i do this rand()%2 it gives me the same think still. grrr!
____"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie
Kevlar-X
Kevlar-X
When in doubt, read the specifications of the function in question.
(or as we used to say, RTFM :).)

A good place to look is MSDN:

rand()
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_rand.asp

srand()
http://msdn.microsoft.com/library/default.asp?url=/library/en-us/vclib/html/_crt_srand.asp

[EDIT]
I noticed you also seem to be having problems with the % (modulus) operator.

What it does is return the remainder of a division between two numbers.

EG: 10 % 10 gives zero, as ten divides ten evenly.
Wheras 10 % 5 yields 5.
[/EDIT]
- Jacob
"1 is equal to 2 for significantly large quantities of 1" - Anonymous
kingnosis
kingnosis
If I remember correctly, to get a number between 0 and n, use

rand() % (n + 1)

Also, to seed with time, I usually use:

srand((UINT)time(NULL));

zackriggle
zackriggle
I think the proper funcion to get the time would be GetTickCount.

edit: It doesn't get the time, but rather the number of milliseconds elapsed since the program began execution. This will never (very seldom) be the same, even on the same macine with no other tasks running.
Chozo
Chozo
That's not portable. time(NULL) is better.
raptorstrike
raptorstrike
cool it works thanks guys[grin] btw im using SDL so its SDL_GetTicks for me ;)
____"This just in, 9 out of 10 americans agree that 1 out of 10 americans will disagree with the other 9"- Colin Mochrie

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.