当前位置:网站首页>Qt产生指定范围内随机数(随机字符串)
Qt产生指定范围内随机数(随机字符串)
2022-06-25 17:38:00 【欧特克_Glodon】
1.目的
在编写QT项目时,产生随机数和随机字符串是十分常见的需求,使用qrand函数就能够实现,但是如果不使用种子的话,产生的随机数并不是真正的随机数,而是固定的数字。通常情况下,我们会使用当前时间作为随机数的种子,以产生真正意义上的随机数
2.生成指定范围随机数
Qt产生随机数代码如下:
int getRandom(int min,int max)
{
qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
int num = qrand()%(max-min);
qDebug()<<num+min;
}
3.生成不重复的随机数组
将产生的随机数存放到数组中,在每次产生新的随机数的同时,在随机数列表中检查是否包含该数
如果包含则重新生成,直到生成新的随机数为止。
int getRandom(int min,int max)
{
QList<int> list;
int i,j;
bool res = true;
qsrand(QTime(0, 0, 0).secsTo(QTime::currentTime()));
for (int i=0; i<10; i++) {
int num = qrand()%(max-min)+min;
list.append(num);
while(res)
{
for(j=0;j<i;j++)
{
if(list[i]==list[j])
break;
}
if(j<i)
{
list[i] = qrand()%(max-min)+min;
}
if(j==i)
res=!res;
}
}
}
4.产生随机字符串
产生随机字符串代码如下:
QString getRandomString(int length)
{
qsrand(QDateTime::currentMSecsSinceEpoch());
const char ch[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
int size = sizeof(ch);
char* str = new char[length + 1];
int num = 0;
for (int i = 0; i < length; ++i)
{
num = rand() % (size - 1);
str[i] = ch[num];
}
QString res(str);
return res;
}
边栏推荐
猜你喜欢

College Students' hot summer exchange, Rog star product phantom 16 flipped version / phantom 13 / phantom x appointment

什么是算子?

WARNING: Unsupported upgrade request.
![Jerry's ADC_ get_ Incorrect voltage value obtained by voltage function [chapter]](/img/7a/9c4f4f800c3142ffc279b70354a0bc.png)
Jerry's ADC_ get_ Incorrect voltage value obtained by voltage function [chapter]

【Matlab】数值微积分与方程求解

使用DiskGenius拓展系統盤C盤的容量

智能对话01-redis的安装
![[machine learning] case study of college entrance examination prediction based on multiple time series](/img/d8/a367c26b51d9dbaf53bf4fe2a13917.png)
[machine learning] case study of college entrance examination prediction based on multiple time series
![How Jerry used to output a clock source to the outside world [chapter]](/img/ea/161be6416726bcd80bb2823a5f6389.png)
How Jerry used to output a clock source to the outside world [chapter]
![Precautions for the use of Jerry's wake-up mouth [chapter]](/img/01/3bfba9a486eb7fa3c0a888bb3ea2d2.png)
Precautions for the use of Jerry's wake-up mouth [chapter]
随机推荐
Learning Tai Chi maker mqtt (II) basic principles of mqtt
观察者模式之通用消息发布与订阅
启牛的涨乐财付通如何?安全靠谱吗
How to solve the problem of network disconnection after enabling hotspot sharing in win10?
杰理之系统时钟设置出现复位或无效问题【篇】
杰理之定时器使用注意事项【篇】
视频制作素材网站整理
Golang sort slice int
用连续自然数之和来表达整数
Mobx学习之路----强大的“状态管理工具”
Unity technical manual - interference / noise sub module
Precautions for using Jerry's timer [chapter]
[machine learning] case study of college entrance examination prediction based on multiple time series
WARNING: Unsupported upgrade request.
杰理之增加加密文件播放功能【篇】
Py3.6 and py3.7 installed by CONDA
卷积操作的本质特性+TextCNN文本分类
Treasure and niche Chinese painting 3D texture material website sharing
使用DiskGenius拓展系統盤C盤的容量
Jerry's system clock setting is reset or invalid [chapter]