Home > Software engineering >  QRandomGenerator gives all the time same values
QRandomGenerator gives all the time same values

Time:11-03

im new in QT/c so i have one question, QRandomGenerator genereate same numbers all the time ? I try to make something, random choice a vectors:

    int index;
    QRandomGenerator num = QRandomGenerator();
    index = num.bounded(6);
    if (index == 0){
        return dmpcY1;
    }else if (index == 1){
        return dmpcY2;
    }else if (index == 2){
        return dmpcY3;
    }else if (index == 3){
        return dmpcY4;
    }else if (index == 4){
        return dmpcY5;
    }else if (index == 5){
        return dmpcY6;
    }else if (index == 6){
        return dmpcY7;
    }

and that isnt work. All the time i get same dmpcY1 (in the same program cycle). bb

I expecting every time when i push the button, code choice different dmpc.

CodePudding user response:

Please consider taking another look at the documentation for QRandomGenerator:

You are always creating a new random generator while using the default constructor with seed value of 1, resulting in always the same pseudorandom number to be generated

QRandomGenerator::QRandomGenerator(quint32 seedValue = 1)

Initializes this QRandomGenerator object with the value seedValue as the seed. Two objects constructed or reseeded with the same seed value will produce the same number sequence.

As stated in the documentation it might be better to use QRandomGenerator::global()

QRandomGenerator::global() returns a global instance of QRandomGenerator that Qt will ensure to be securely seeded. This object is thread-safe, may be shared for most uses, and is always seeded from QRandomGenerator::system()

  •  Tags:  
  • c qt
  • Related