PDA

View Full Version : Using Qrand in qt



samira
29th June 2013, 12:30
hi,I want to know ,how to use generate value with qrand in qt?

saman_artorious
29th June 2013, 12:31
Call
qsrand(QTime::currentTime().msec()) once on application start. It will seed the random number generator.

Then generate the random numbers:

int nextNumber = rand() % 15 + 1;

saman_artorious
29th June 2013, 14:47
did it work fine?

samira
29th June 2013, 14:53
For converting range of

rand()(0-255)
into 0-1,is it correct if I use this code?

float nextNumber = (rand() % 10000) / 10000.0;

Added after 4 minutes:

yes it seems work correct,but i want to sure about it

saman_artorious
29th June 2013, 14:54
Yes, this is correct.

ChrisW67
29th June 2013, 23:08
hi,I want to know ,how to use generate value with qrand in qt?

Assuming you want an integer value in the range 0 to N-1 for N < RAND_MAX then you just do this:

int value = qrand() % N;

However, it seems you wanted a random real value in the range 0 to 1.0, which qrand() does not produce directly:

qreal value = static_cast<qreal>(qrand()) / RAND_MAX ;
Be aware that RAND_MAX is typically fairly small and may give wide gaps between possible "random" floats.

Neither approach is suitable for cryptographic applications or where the uniformity of the random distribution is very important.