Thomas is correct and something I have to wrestle with from time to time. And there will be a level of predictability in all random numbers generated with rand().
Even though you seed your generator with time(), the code runs to fast. Hence the time doesn't change if you are reseeding between calls to rand(). There are two very simple fixes. Either place a sleep() _or_ Sleep() call between the srand() calls so that some time has passed for a new seed to populate the generator. _OR_ use the first result in dieOne to seed the value for dieTwo. Simple example combining the two: srand( time(0) ); // Get the seconds from epoch dieOne = 1 + rand() %6; // Get a random number from 1 to 6 sleep( dieOne ); // Sleep for the random number of seconds. srand( time(0) % dieOne ); // Reseed based on time and the result from dieOne. dieTwo = 1 + rand() %6; // Get a random number from 1 to 6 There are more complex and even some faster ways to get random numbers. But I think this will do nicely for what you are doing. On Wed, 2008-01-16 at 20:55 -0700, Thomas Hruska wrote: > onecrazeemom wrote: > > I finally completed the dice roll program. Now, what do I do to make > > the rolls more random? They seem to come up with doubles quite > often. > > I used srand( time(0)) to get my random numbers. I used the > modulus(I > > think that is what it is called) > > > > dieOne = 1 + rand() %6; > > dieTwo = 1 + rand() %6; > > > > srand( time(0) ); > > > > Just curious what gives you a true random number when the lines of > > code are run so close together. Here are a couple of rolls: > > > > 1. 3, 1 > > 2. 6, 1 > > 3. 6, 2 > > 4. 5, 5 > > 5. 1, 1 > > 6. 3, 4 > > 7. 4, 6 > > > > I guess they are more random than I thought, but the first two times > I > > ran the program it came up with doubles. > > > > Thanks in advance, > > Stephanie > > Probably what you are "experiencing" is the side effect of using the > modulus of a random number with a number not evenly divisible by the > maximum range of the random number generator. > > True random number generators are MUCH harder to create (all the > implementations of rand() that I've seen are simple congruential > pseudorandom generators). You get into heavy math and/or cryptography > VERY quickly if you start rolling your own. > > If you need something fancier than the built-in rand(), look at > Mersenne > Twister. > > srand(time(NULL)); > > Creates predictable numbers. If I can roughly guess your system > clock's > current time, I can know the exact numbers that are going to be > output > from the rand() function. > > -- > Thomas Hruska > CubicleSoft President > Ph: 517-803-4197 > > *NEW* MyTaskFocus 1.1 > Get on task. Stay on task. > > http://www.CubicleSoft.com/MyTaskFocus/ > > > > >
