Qt Snippet: random number generator
Please note that in this case using the same seed number multiple times will have the consequence that the sequence of numbers generated will be always the same every time. For this reasons is very important to set a "casual" seed number at each new call. The common practice is to use the current millisecond time at the moment of initialization call as follow:
qsrand(static_cast<uint>(QTime::currentTime().msec()));
The qsrand() function must to be call only once usually at program startup. Another important note is this function is thread dependent. This mean you have to call this function for set the seed number from inside the thread where you'll need to get the random numbers. For example in case you need to get a random number in the main thread and in a secondary thread you'll have to call srand() two times at beginning of both threads. Once clarified this point the function for get a random number included between a min and max value is the following:
int GetRandomNumber(const int Min, const int Max) { return ((qrand() % ((Max + 1) - Min)) + Min); }
Each time you'll call this function you'll get a different number in the requested range.
Comments
Post a Comment