-
QRandomGenerator数类(高质量随机)
#include <QRandomGenerator>
种子值(seed)是为了确保随机数序列的可重复性,可预测性(类似随机数参数的序列规则,如果多个随机数,是相同的随机种子,那么在相同范围内,出现相同值的几率会越大?)
种子值和随机数生成器之间是初始化和生成序列的关系,如果使用了global(),system()等随机数生成器就不需要手动产生种子值了
//手动设置种子值 quint32 seed = 1234; QRandomGenerator customGenerator(seed); customGenerator.bounded(100);//[0,99]
随机数发生器
-
QRandomGenerator::global() //短期内使用,生成数量较小
QRandomGenerator globalGenerator = QRandomGenerator::global(); //生成一个随机整数[0,99] int randomInt = globalGenerator.bounded(100); //随机产生一个随机双精度浮点数(0.0,1.0) globalGenerator.generateDouble();
2.QRandomGenerator::system()//需要高质量,不可预测的随机数的场景(加密,游戏等)
QRandomGenerator ranSys = QRandomGeneratro::system(); int value = ranSys.bounded(100);
3.QRandomGenerator::securelySeeded() //需要安全性和不可预测性的随机数生成场景非常有用(加密,密码生成,令牌生成)
QRandomGernerator ranse = QRandomGenerator::securelySeeded();
-
QRandomGenerator的接口函数
-
generate() //int32位随机数
-
generate64() //64位随机数
-
generateDouble() //[0,1)浮点数
-
括号运算符()
QRandomGenerator rand(QDateTime::currentSecsSinceEpoch());//不断变化种子值,确保随机序列每次都不一样 rand();//类似 rand.generate()
-
bounded(highest)//[0,highest)
bounded(可以设置不同类型) bounded(lowest,highest)//[lowest,highest)