Qt qrand in loop on Windows generates the same numbers

I have a qt application using qml. qrand in loop is not working correctly, in code is working correctly. This issue only appears on windows (used on Windows 7 and 8 with MSVC2012_OpenGL_32bit). Here's an example:

In main.cpp, on startup, I print:

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

      

then in the loop 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;
    }
}

      

there are 2 different numbers in the output, repeating about 200 times and then changes:

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

      

If I use qrand not in a loop, it works correctly. But, if I create a function that generates random numbers with qrand, this function does not work correctly. On linux on gcc 64-bit compiler the same code works correctly, it generates different numbers on each line. On Windows 7 and 8 with MSVC2012_OpenGL_32bit qrand does not work correctly. Also, I've tried the standard srand and rand (), it doesn't work as well. I checked (uint) time.msec (), it is always different. But if I put qsrand in a loop program, it 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;
    }
}

      

The output is not ideal, because qrand only generates different numbers more often, but again not always.

UPDATE: I tried C ++ 11 randomly on windows and it works. I haven't tried this on Linux yet. But the question about qrand is still alive.

C ++ 11 case I used: random std functions don't work - Qt MinGw

+3


source to share


2 answers


My answer is using C ++ 11 random lib: random std functions don't work - Qt MinGw



I don't have time for deep research on this issue, so its the easiest way to solve this problem.

0


source


Since the random value is clock-based, if you use random in a loop (which is very fast), the hours don't change and your numbers are the same.



You must add a pause statement to change the hours.

+1


source







All Articles