Sign in to follow this  

Newbie srand() question...

This topic is 3596 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
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

This topic is 3596 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this