Jump to content
  • Advertisement
Sign in to follow this  
Chrono1081

Newbie srand() question...

This topic is 3846 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Hello, I am writing a program where I need to generate three random numbers quickly. The problem I am running into is that the numbers do not generate fast enough to keep from being the same number. I used to cheat and use the wait() so that a different number would be generated but I cant do that with this program. Here is a code snippet so you can see what is going on. Any help would be greatly appreciated :D This is C++ by the way.
 srand(time(0)); 

Theres my seed at the beginning of the main(), and here is what I have my variables set to (there are 3 of these all in different functions with different names).
powerSetting=rand() % 9 + 1;

Share this post


Link to post
Share on other sites
Advertisement
The problem you're having right now stems from the fact that the time() function returns seconds. That means that if you run your program twice in the same second, you'll get the same random number sequence. The solution is to use a higher precision timer. For example, on Windows, GetTickCount() has a resolution of ~15ms. So you only need to wait 15ms between calls to your program.

Share this post


Link to post
Share on other sites
Only seed the pseudo-random number generator once in your program's lifetime. This will ensure that the sequence generated by rand() will be pseudorandom.

srand(time(0)); 
int a = rand() % 9 + 1;
int b = rand() % 9 + 1;
int c = rand() % 9 + 1;


Or are you having problems with executing the same program several times in a row?

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!