欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

随机数生成器

程序员文章站 2024-03-19 11:55:04
...

std中有个高效的伪随机数生成器std::mt19937, 头文件为random, 指定不同随机数种子后即可. 可以取时间作为种子.

#include <QCoreApplication>
#include <QDebug>
#include <QDateTime>
#include <random>

int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
qint64 time1, time2;

for (int i = 0; i < 10; ++i) {
time1 = QDateTime::currentMSecsSinceEpoch();

do {
time2 = QDateTime::currentMSecsSinceEpoch();
} while (time1 == time2);

std::mt19937 mt2(time2);
qDebug() << mt2();
}

return a.exec();
}



结果:

237930843

238842087

1128193202

2130824632

2217341519

880128304

2166686048

2460956254

946329442

2390559192

由于计算机运输速度太快, 取得的时间可能会相同,生成的随机数也会相同,(最先在这里还纠结了好半天, 解决方案, 循环取时间,等时间不一样了再将它作为种子,方法很简单也很有效, currentMSecsSinceEpoch取的时毫秒). 

转载于:https://my.oschina.net/kshuang/blog/1581750

上一篇: P2776 [SDOI2007]小组队列

下一篇: