I am having two problems with the function qrand().
1) in "randInt1", every time I run the program, it always returns the same numbers: 41, 85, 72, 38, 80, 69, 65, 68, 96, 22.
2) in "randInt2", he often repeats the numbers.
How can I create random numbers that are not repeated, and are not the same whenever I run the program?
#include <QtCore/QCoreApplication>
#include <QTime>
#include <QDebug>
int randInt1(int low, int high) { // returns a random integer value between low and high
return qrand() % ((high + 1) - low) + low;
}
int randInt2(int low, int high) { // returns a random integer value between low and high
QTime time = QTime::currentTime(); qsrand
((uint
)time.
msec());
// synchronizes with the current time return qrand() % ((high + 1) - low) + low;
}
int main(int argc, char *argv[]) {
for (int i = 0; i < 10; i++) qDebug() << "Rand1: " << randInt1(0, 100);
qDebug() << "\n\n";
for (int i = 0; i < 10; i++) qDebug() << "Rand2: " << randInt2(0, 100);
return a.exec();
}
#include <QtCore/QCoreApplication>
#include <QTime>
#include <QDebug>
int randInt1(int low, int high) { // returns a random integer value between low and high
return qrand() % ((high + 1) - low) + low;
}
int randInt2(int low, int high) { // returns a random integer value between low and high
QTime time = QTime::currentTime(); qsrand((uint)time.msec()); // synchronizes with the current time
return qrand() % ((high + 1) - low) + low;
}
int main(int argc, char *argv[]) {
QCoreApplication a(argc, argv);
for (int i = 0; i < 10; i++) qDebug() << "Rand1: " << randInt1(0, 100);
qDebug() << "\n\n";
for (int i = 0; i < 10; i++) qDebug() << "Rand2: " << randInt2(0, 100);
return a.exec();
}
To copy to clipboard, switch view to plain text mode
Bookmarks