1.c++11提供的random实现了随机数库,它通过随机数引擎类(random_number_engines)产生随机数序列,随机数分布类(random-number distribution)使用随机数引擎生成服从特定概率分布的随机数。
#include <iostream>
#include <random>
std::default_random_engine e;
std::uniform_real_distribution<double> random(0,1);
void SerialPortWidget::slotTest()
{
qDebug()<<"r:"<<random(e)<<"i:"<<int(random(e)*255);
//QColor color=QColorDialog::getColor(Qt::red,this,"选择颜色");
btnTest->setStyleSheet("background-color:rgb("+QString::number(int(random(e)*255))+","
+QString::number(int(random(e)*255))+","
+QString::number(int(random(e)*255))+");");
}
private:
std::default_random_engine randomEngine;
std::uniform_real_distribution<double> randomNum;
OperationWidget::OperationWidget(QWidget *parent) : QWidget(parent),
randomNum(0,1)
{
this->setMaximumWidth(400);
initUI();
}
QColor OperationWidget::getRandomColor()
{
QColor c=QColor(int(randomNum(randomEngine)*255),int(randomNum(randomEngine)*255),
int(randomNum(randomEngine)*255));
return c;
}
2.随机整数
private:
std::default_random_engine randomE;
std::uniform_int_distribution<int> randomNum;
void EscBusWidget::randomTestThread()
{
randomNum=std::uniform_int_distribution<int>(0,100);
threadRandomTest=std::thread([&](){
while(isRandomTest){
qDebug()<<"r:"<<randomNum(randomE);
for(int i=0;i<randomTime;i++)
{
if (!isRandomTest)
{
break;
}
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
}
});
threadRandomTest.detach();
}
来源:oschina
链接:https://my.oschina.net/u/4333022/blog/3323724