Advertisement

Random numbers

Started by September 25, 2001 09:42 PM
4 comments, last by BurningGoat 23 years, 4 months ago
I have a program that is supposed to generate a random number each time the spacebar is pressed, but I get the same "random" numbers every time (first time: {1, 4, 7, 9, 3}, next time: {1, 4, 7, 9, 3}, etc.). I''m using the rand()%(highest random number) to get my numbers. I''m pretty sure that you can seed the random number generator to get more "random" numbers, but I forgot how from my high school comp. sci. days. Any help would be greatly appreciated. If you don''t have anything to say, then don''t say it at all.
If you don't have anything to say, then don't say it at all.
add this to your init code

srand((unsigned)time(NULL));

and make sure you have time.h and math.h included
www.EberKain.comThere it is, Television, Look Listen Kneel Pray.
Advertisement
You need to seed the generator each time the program starts with the current time, so that it will be different each time the program runs. If you don''t, the same seed will be used and you''ll get the same results each time, like you are now.

To seed:

srand((unsigned)time(NULL));
Ok, thanks. That worked perfectly.




If you don''t have anything to say, then don''t say it at all.
If you don't have anything to say, then don't say it at all.
If you take a big enough sample, you will find that eventually the numbers will repeat them selves. Not the same number over and over gain, just the same pattern. If you rand() in several places in your code, or it gets called a random number of time, it''s not that important since each call to rand() will get a random unknown chunk of the pattern, which will change each time around. And even if you don''t, it''s not usually that important.

There are times when having not-so-random random numbers is useful, like when debugging, or using the random number generator to encrypt data. (if you use it for the last one, keep in mind that different librarys can give different numbers with the same seed!)

Useless information no normal person would want to know.
Also, using the % operator can make your numbers a lot less random.

Do something more like this:

rand()/RAND_MAX * highest_num

This topic is closed to new replies.

Advertisement