i know there is a way to make this function:
return a completely random number using something from time.h but cant figure it out, anyone got a suggestion or an alternative?Code:rand();
i know there is a way to make this function:
return a completely random number using something from time.h but cant figure it out, anyone got a suggestion or an alternative?Code:rand();
Then just call rand(); and you can use % to limit it.Code:srand((unsigned)time(0));
I think it talks about this in the FAQ.
Everything you need to know about random numbers: FAQ
Don't quote me on that... ...seriously
I just posted a program using the system clock as the Seed, then a random generated number as follows:
Code://SEED THE RANDOM NUMBER WITH SYSTEM CLOCK srand(static_cast<unsigned int>(time(0))); //GENERATING A RANDOM NUMBER FROM 1 - 100 random_number = (rand() % (100 - 1 + 1)) + 1;
I heard somewhere that the highest-order bits are the "most random". If you really care about that, I think this does the trick:
Code:int RandomNumber(int min, int max) { static int seeded = 0; if (seeded == 0) { srand(time(NULL)); seeded = 1; } return rand() / (double)RAND_MAX * (max - min + 1) + min; }
Don't quote me on that... ...seriously
For information about high order bits and most-randomness and all that, see Prelude's article: http://eternallyconfuzzled.com/arts/jsw_art_rand.aspx
dwk
Seek and ye shall find. quaere et invenies.
"Simplicity does not precede complexity, but follows it." -- Alan Perlis
"Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
"The only real mistake is the one from which we learn nothing." -- John Powell
Other boards: DaniWeb, TPS
Unofficial Wiki FAQ: cpwiki.sf.net
My website: http://dwks.theprogrammingsite.com/
Projects: codeform, xuni, atlantis, nort, etc.