Using rand() ina class
| graciano (28) | |||||
| Hi! I was building a simple example of a class that represents a "dice". At this point i have: Dice.h
And i tested it with ... game.cpp
The problem is that i get always the same numbers. How can i make the number generation more random without complicating too mush (because that is not the main subject here)? Showl i use srand ant time?! Thanks | |||||
| jsmith (958) | |||
| srand( time( 0 ) ); as the first line in main(). | |||
| Bazzy (546) | |||
| I would suggest calling srand(time(0)) in the class constructor | |||
| jsmith (958) | |||
| That would reseed the RNG every time a Dice was constructed and would go against the rule of seeding only once. | |||
| Bazzy (546) | |||
Not if done in this way:
So the programmer can use the Dice class without calling srand (Edit) What's wrong in seeding few times? | |||
| jsmith (958) | |||
| It is recommended that the RNG be seeded only once to generate "better" RNGs. The above works, though I still would advocate moving the srand() to main() because now only Dice can call srand() in the entire application (which might not be a problem for the above application, but then consider a larger application that has a Coin class and a Flip() method -- now does Dice init the RNG, or does Coin, or both, or neither?). I don't think it should be Dice's responsibility to do that. In a truly object oriented, flexible architecture I would allow the user to construct a Dice with a random number generator function (using rand() as the default) along the same lines as the random_shuffle() standard algorithm. | |||
| graciano (28) | |||
| I will use srand() in main, because otherwise i will be running away from my initial idea. One of this days, with a little more time, i will try adding a "shuffle" method to the class so that who decides to use the class as not to worry about about the way random numbers are generated. Thanks again | |||
Registered users can reply in this forum.
