Public Group

Newbie srand() question...

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

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 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 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?

1. 1
Rutin
65
2. 2
3. 3
4. 4
5. 5

• 16
• 10
• 29
• 20
• 9
• Forum Statistics

• Total Topics
633415
• Total Posts
3011767
• Who's Online (See full list)

There are no registered users currently online

×