auther: abinng date: 2026-03-20 21:05
createDate:2026-03-20 21:05
前言
Qt5 中是 QRandom 类,Qt6 中是
QRandomGenerator 类
在计算机中,随机数的生成本质上是基于初始‘种子’的复杂数学计算。如果种子固定,生成的随机数序列就是可预测的。
为了生成高质量、安全的随机数,现代操作系统会在底层收集硬件噪音、外部输入等物理混沌现象建立
‘熵池 (Entropy Pool)’ ,Qt
通常会结合操作系统底层的‘熵池’来自动获取极其随机的初始种子。
固定种子
我们用 QRandomGenerator
类的实例对象生成一些固定种子的随机数,打印试试
1 2 3 4 5 6 7 8 9 10 11
| #include <QRandomGenerator> #include <QDebug>
int main() { QRandomGenerator *gen = new QRandomGenerator(1);
for (int i = 0; i < 9; ++i) { qDebug() << gen->generate(); } return 0; }
|
运行两次:
1 2 3 4 5 6 7 8 9 10
| 853323747 2396352728 3025954838 2985633182 2815751046 340588426 3587208406 298087538 2912478009
|
可见固定种子,会生成同样的序列
用时间当种子
QDateTime 类中有两个静态方法获取当前的时间戳:
QDateTime::currentSecsSinceEpoch() :以秒为单位
QDateTime::currentMSecsSinceEpoch():以毫秒为单位
1 2 3 4 5 6 7 8 9 10 11 12 13
| #include <QRandomGenerator> #include <QDebug> #include <QDateTime>
int main() { QRandomGenerator *gen = new QRandomGenerator();
gen->seed(QDateTime::currentMSecsSinceEpoch()); for (int i = 0; i < 5; ++i) { qDebug() << gen->generate(); } return 0; }
|
运行两次:
1 2 3 4 5 6 7 8 9 10 11 12
| 1235559159 535938647 3192203312 3566839314 2092769160
2021524794 3109484075 2861288850 1218765550 3918871412
|
显然结果不同了
QRandomGenerator 类中还有一个成员函数是
bounded(x, y) 返回 [x, y)
区间的随机数,相当于获取随机数后,加了一个取余的操作,但是融进一个函数(bounded)了
使用如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| #include <QRandomGenerator> #include <QDebug> #include <QDateTime>
int main() { QRandomGenerator *gen = new QRandomGenerator();
gen->seed(QDateTime::currentMSecsSinceEpoch()); for (int i = 0; i < 9; ++i) { qDebug() << gen->bounded(0, 10); } return 0; }
|
当然运行两次的结果还是不一样
这里只是简单了解一下使用,可以当作一个小知识,用于后面的实践