如何在Qt中重新设置qrand()?

问题描述 投票:0回答:2

我在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()以使其更随机?谢谢。

qt seed
2个回答
3
投票

我找到了一个解决方案......我将它添加到构造函数中,因此程序每次都以不同方式播种。它适用于我的目的。

QDateTime cd = QDateTime::currentDateTime();
qsrand(cd.toTime_t());

0
投票

作为@Yep答案的替代方案,由于自QDateTime::toTime_t()以来Qt5.8已弃用,以下内容同样适用:

qsrand(QDateTime::currentMSecsSinceEpoch()%UINT_MAX);
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.