Qt random numbers

related functions    

qsrand(unsigned seed);
qrand ();

These two functions are in #include <QtGlobal>

The random numbers generated by the above functions are pseudo-random numbers. Pseudo-random numbers are called for two reasons:

      1: qsrand is used to set a seed, which is the starting value for qrand to generate random numbers. For example, qsrand(10), set 10 as the seed, then the random number generated by qrand is between [10, 32767]

         (RAND_MAX == 32767). If qsrand() has not been called before qrand(), then qrand() will automatically call qsrand(1), that is, the system defaults to 1 as the starting value of the random number.

       2: The reason why it is called a pseudo- random number is that when the value of the seed is the same, the random sequence generated by the function running twice is consistent .

Note: The qrand() function generates a random sequence, but only returns one value at a time. An example is as follows:

#include <QTime>
#include <QtGlobal>
#include <QDebug>


void generateAscendRandomNumber()
{
    int i;
    QList<int> numbersList;
    qsrand(10);
    for(i=0;i<10;i++)
    {
        numbersList.append(qrand()%10);
    }
    qSort(numbersList.begin(),numbersList.end());
    for(i=0;i<10;i++)
    {
        qDebug()<<numbersList[i];
    }
}

intmain ()
{
    generateAscendRandomNumber() ;
}

The above output is: 1 2 2 2 4 6 6 7 9 (actually will wrap)

Running the program multiple times found that the output was consistent. Because the seed is unchanged, the random sequence generated by running qrand() multiple times is consistent.

The seeds are the same, and each number in each random sequence is random, but the random sequences are not random.

 

In order to obtain different random sequences, the current time can be used as a seed to simulate random numbers. Because the time is constantly changing, that is, the value of the seed is also different, so the random sequence generated is also different.

qsrand(QTime(0,0,0).secsTo(QTime::currentTime()))

In fact QTime(0,0,0).secsTo(QTime::currentTime()), the returned value is the value from 0 to QTime::currentTime().

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324610660&siteId=291194637