amol01
amol01

Reputation: 1863

qrand is returning always 0

I need to get random numbers between 0 and 1. As 0.54321, 0.8912, 0.1234342, 0.0000123 and etc

I put this code in my main and also Application constructor:

       qsrand(QDateTime::currentDateTime().toTime_t());

And used this code inside one of my slots:

       float prob = qrand() % 1;

I tried int, double as a return value, but it is always returning 0.

Any ideas what is going on?

Thanks

Upvotes: 0

Views: 1022

Answers (1)

haccks
haccks

Reputation: 106012

qrand() generates integer numbers between 0 to RAND_MAX and every number is perfectly divisible by 1 and giving remainder as 0. Try this instead:

 float prob = (float) qrand() / (RAND_MAX+1); // 1 is exclusive

Upvotes: 4

Related Questions