Advertisement

Random numbers

Started by February 23, 2000 11:07 PM
6 comments, last by paulcoz 24 years, 6 months ago
Does anybody know how to use rand (VC6++) correctly. I got the same list of "random" numbers over and over. I tried using the companion function setrand(?) to "seed" the generator but couldn''t get it to work. I would like to be able to specify the range of the values generated. Perhaps there is a better way? Any help appreciated, Paulcoz.
if you mean you get the same list whenever you run the program then just use srand()
don''t just put a number in there.. use the timer.. something like:
srand( (unsigned)time( NULL ) );

that''ll seed a diff number all the time. just stick it in the start of the program.
-werdup-
Advertisement
Now that you mention "time" and "srand" I remember trying those as well.

Is there some reason srand goes at the start of the program?

I will try again, thanks,
Paulcoz.
srand goes at the start because you must seed the generator before you use it. It doesn''t have to be right at the start though, just before you ever call rand, or any other function that uses it.

------------------------------
Jonathan Little
invader@hushmail.com
http://www.crosswinds.net/~uselessknowledge
Just to make sure it''s obvious... you only need to do an srand once in your entire program. That''s why so many people put it at the beginning, so they know that whenever they use the random number generator they''re sure it''s been seeded already.

-fel
~ The opinions stated by this individual are the opinions of this individual and not the opinions of her company, any organization she might be part of, her parrot, or anyone else. ~
And another thing that many map generators do, is allow the player to put the seed in. Like in Seven Kingdoms you could type in the map id. The game doesn''t need to store the map, just before generation it can seed the number generator, and it will regenerate the map under the same conditions and after its done, set it back to the timer....

Another thing, this can be used on network games, where the server picks the seed based off of its timer, and passes that seed to the other machines so they are all ''in sync'' with the same number generation methods.


Advertisement
(beating a dead horse)

Also, I find using the same seed while debugging is invaluable, so your randomness can be predictable. I usually set my srand to 0 for debug build, and on current time for release build.
After you''ve seeded with srand you need a function that''ll give a you a specified range of values

int nGenRandom (int start , int end )
{
return ( (rand () % (end - start + 1)) + start);
}

...
int RandomChoice = nGetRandom(0, 5);

Gives you a random number 0 to 5 inclusive

ZoomBoy
A 2D RPG with skills, weapons, and adventure.
See my character editor, Tile editor and diary at
http://www.geocities.com/Area51/Atlantis/7739/

This topic is closed to new replies.

Advertisement