简体   繁体   中英

Qt rand() doesn't work properly

I want to show 1000 random numbers from 0 to 99 999. But there is a kinda weird problem with that. It shows 1000 numbers but none of them is higher than aprox. 35 000. Why is that?

#include "mainwindow.h"
#include <QApplication>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    int ran;

    qsrand(qrand());

    for (int i=0; i<1000; i++){
        ran = qrand() % 100000;
        qInfo() << ran;
    }    

    return a.exec();
}

What console showed me is:

18103 76 22033 25191 5349 13724 11988 25919 32568 20303 17393 14983 4038 443 16566 18275 8687 23110 24124 31899 20267 2336 22086 3570 6406 29490 32107 13236 29800 8273 18552 10895 6682 22968 16656 26019 16518 3253 11669 9948 8894 17826 28748 29056 30912 22295 25019 2820 17657 350 10838 32292 6919 11815 24411 21555 17347 5245 26363 30895 25215 22777 26554 31512 32652 32310 18200 8962 7168 14724 31601 2666 12981 32737 13602 12870 19093 24357 8941 17759 32277 30588 21919 32099 7168 10521 1775 24118 17782 18985 18346 15242 11572 30982 22797 15535 23574 24238 13682 21164 7897 30067 3120 21646 294 10228 13500 13824 31180 23627 23828 3100 11342 16264 30557 21633 25501 25951 10954 12966 10790 4125 19393 5998 8975 13536 7993 1788 2238 4104 28007 28872 29852 24041 10137 19954 21528 3010 9570 31191 12014 29939 15607 30947 8873 106 15065 8614 14182 12895 31924 23593 29148 1601 13191 27522 18073 9456 4358 30118 21134 19244 25661 15743 31950 29774 26997 17214 26003 7477 20827 16115 18050 13188 17247 10586 10288 1291 24411 18168 4324 17282 629 26983 4255 28797 21318 23279 20057 17820 22844 10326 31374 27906 9020 15608 19193 7689 16780 1306 25504 29236 5873 2683 20752 1638 17684 16172 30698 15441 14378 27298 7582 12336 5588 27914 28279 14009 4932 19676

See? None of these numbers are higher than 35000. What did I wrong?

Issue

Actually it is 32767. The behavior in this case is identical to the standard rand() :

Returns a pseudo-random integral number in the range between 0 and RAND_MAX .

And the similar statement in the qrand() docs:

Returns a value between 0 and RAND_MAX (defined in <cstdlib> and <stdlib.h> ).

Obviously the RAND_MAX in your case is equal to 32767 (2¹⁵ – 1).

Solution

The solution is to use C++11 random number generators:

#include <random>

// ...

std::random_device rd;
std::mt19937 mt(rd());
const int min = 0;
const int max = 99999;
std::uniform_int_distribution<int> ds(min, max);
for (int i = 0; i < 1000; ++i) {
    qDebug() << ds(mt);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM