vendredi 26 décembre 2014

Qt qrand in cycle in Windows generate same numbers

I have qt application using qml. qrand in cycle works wrong, in code works right. This problem appears only at windows. Here is example:


In main.cpp at begin i print:



QTime time = QTime::currentTime();
qsrand((uint)time.msec());


then in cycle i use qrand



for (int j = 0; j < 4; j++)
for (int i = 0; i < 1000; i++){
int r1 = qrand() % 150;
int r2 = qrand() % 150;
qDebug() << r1 << r2 << endl;
}


in output there are 2 different numbers repeats about 200 times, then changes:



8 58
8 58
8 58
...
120 1
120 1
120 1
...


if i use qrand not in cycle, it works right. But, if i make function, that generates random numbers with qrand this function works wrong. In linux on gcc 64 bit compiler the same code works right, it generates different numbers in every line. In windows 7 and 8 with MSVC2012_OpenGL_32bit qrand works wrong. Also, i tried standard srand and rand(), it also works wrong. I checked (uint)time.msec(), it is always different. But if i put qsrand into cycle program generates not perfect, but different numbers:



for (int j = 0; j < 4; j++)
for (int i = 0; i < 1000; i++){
QTime time = QTime::currentTime();
qsrand((uint)time.msec());
int r1 = qrand() % 150;
int r2 = qrand() % 150;
qDebug() << r1 << r2 << endl;
}


Output not perfect couse it qrand just generates different numbers more often, but again not always.


UPDATE: i tried c++11 random in windows and it works. I didn't try it in linux yet. But the question about qrand is still alive.


The c++11 random which i used: std random functions not working - Qt MinGw





Aucun commentaire:

Enregistrer un commentaire