C++11 随机数和随机颜色

允我心安 提交于 2020-12-08 04:51:17

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();
}

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!