如何在 Qt 中重新播种 qrand()?
how to reseed qrand() in Qt?
我在 Qt 中使用这个生成随机字符串:
GenerateRandomString()
{
const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
const int randomStringLength = 5; // assuming you want random strings of 5 characters
QString randomString;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
return randomString;
}
然而,每次我启动调试(或 运行 程序)时,它生成的字符串都会重复。似乎 qrand() 每次都播种相同的种子。我怎样才能正确地重新播种 qrand() 以使其更随机?谢谢。
我找到了解决方案...我将其添加到构造函数中,因此程序每次都以不同的方式播种。它对我有用。
QDateTime cd = QDateTime::currentDateTime();
qsrand(cd.toTime_t());
作为@Yep 答案的替代方案,由于 QDateTime::toTime_t()
自 Qt5.8
以来已被弃用,因此以下内容同样有效:
qsrand(QDateTime::currentMSecsSinceEpoch()%UINT_MAX);
我在 Qt 中使用这个生成随机字符串:
GenerateRandomString()
{
const QString possibleCharacters("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789");
const int randomStringLength = 5; // assuming you want random strings of 5 characters
QString randomString;
for(int i=0; i<randomStringLength; ++i)
{
int index = qrand() % possibleCharacters.length();
QChar nextChar = possibleCharacters.at(index);
randomString.append(nextChar);
}
return randomString;
}
然而,每次我启动调试(或 运行 程序)时,它生成的字符串都会重复。似乎 qrand() 每次都播种相同的种子。我怎样才能正确地重新播种 qrand() 以使其更随机?谢谢。
我找到了解决方案...我将其添加到构造函数中,因此程序每次都以不同的方式播种。它对我有用。
QDateTime cd = QDateTime::currentDateTime();
qsrand(cd.toTime_t());
作为@Yep 答案的替代方案,由于 QDateTime::toTime_t()
自 Qt5.8
以来已被弃用,因此以下内容同样有效:
qsrand(QDateTime::currentMSecsSinceEpoch()%UINT_MAX);