QT 随机数生成

下面总结了QT中随机生成的方法(仅供学习参考),分为旧方法和新方法,一般来说,旧的方法已经被抛弃,在开发新的应用中推荐使用新方法。

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
 
#include <QCoreApplication>
#include <QDebug>
#include <QTime>
#include <QRandomGenerator>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    
// 旧方法
    // 生成随机数主要用到了函数qsrand和qrand,这两个函数在#include <QtGlobal>中;
    // qsrand用来设置一个种子,该种子为qrand生成随机数的起始值。
    // 比如说qsrand(10),设置10为种子,那么qrand生成的随机数就在[10,32767]之间。
    // 而如果在qrand()前没有调用过qsrand(),那么qrand()就会自动调用qsrand(1),即系统默认将1作为随机数的起始值。
    // 使用相同的种子生成的随机数一样。
    // 在使用qrand()函数产生随机数之前,一般要使用qsrand()函数为其设置初值,如果不设置初值,那么每次运行程序,qrand()都会产生相同的一组随机数。
    qsrand(QTime(000).secsTo(QTime::currentTime()));
    
int nTestNum = qrand() % 100;
    qDebug() << nTestNum;
    
// 新方法(推荐使用)
    qDebug() << QRandomGenerator::global()->bounded(256);
    qDebug() << QRandomGenerator::global()->bounded(
256.0);
    
return
 a.exec();
}

说明:旧方法使用的是qsrand()和qrand()的组合实现方法,精度一般;新方法使用的是QRandomGenerator类,可以提供高精度的随机数实现。

posted on 2019-03-12 10:23  我来乔23  阅读(7447)  评论(0编辑  收藏  举报

导航