Solved: Question about qrand()

  • Hi...
    I make a test of qrand() in my application. I want to make a random integer from 1 to 5. The instruction is:
    qDebug << "ID random: " << qrand() % 5;

    but after tested many times the result always 1. Is there any suggestion? I need your help.
    Thanks in advance.

  • Hi there,
    Do you only call it ones after program startup?
    Then it's the same as the default srand() function in C. It will always hold the same value when not initialised with a value. So you could use the msec time expired since program stated to set the initialised value. That should give you a more random value.

  • Thank for reply. Yes, I only call once in the beginning of Start button action. I hope can catch a random value for the next processing. Still confusing...:)

  • Finally it works, I used srand() in Qt qsrand() and using the code:

    ID=qrand() % 6;
    qDebug << “ID random: “ << ID;

    Thanks for the idea srand().

Log in to reply

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.