成都创新互联网站制作重庆分公司

c++如何产生随机数

这篇文章将为大家详细讲解有关c++如何产生随机数,小编觉得挺实用的,因此分享给大家做个参考,希望大家阅读完这篇文章后可以有所收获。

公司主营业务:成都做网站、网站制作、移动网站开发等业务。帮助企业客户真正实现互联网宣传,提高企业的竞争能力。创新互联建站是一支青春激扬、勤奋敬业、活力青春激扬、勤奋敬业、活力澎湃、和谐高效的团队。公司秉承以“开放、自由、严谨、自律”为核心的企业文化,感谢他们对我们的高要求,感谢他们从不同领域给我们带来的挑战,让我们激情的团队有机会用头脑与智慧不断的给客户带来惊喜。创新互联建站推出益阳免费做网站回馈大家。

c库伪随机数发生器

rand 

srand

大多时候用时间产生随机发生器的seed

int GetRandomNum(int min, int max,int seed)

{

//srand((unsigned)time(NULL)); //生成seed

srand(seed);

return( rand() % (max - min) + min);

}

c++11 引入的伪随机数发生器.随机数抽象成随机数引擎和分布两部分.引擎用来产生随机数,分布产生特定分布的随机数

常用的就是线性均匀分布

uniform_int_distribution 

uniform_real_distribution

std::random_device rd;//来产生一个随机数当作种子

std::uniform_int_distribution uni_dist(0, 9999999); //指定范围的随机数发生器

std::cout << uni_dist(rd) << std::endl;

还有一些其他发生器,如 伯努里分布、泊松分布、正态分布 

// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。

//

#include "stdafx.h"

#include

#include

#include

using namespace std;

class Random {

public:

const static  unsigned int  maxRand = std::random_device::max();

static Random& getInstance()

{

static Random instance;

return instance;

}

unsigned int  getInteger() noexcept {

return (*dist)(rd);

}

unsigned int  GetMTEngineInteger() noexcept {

return (*mtEngine)();

}

uint64_t  GetMTEngine64Integer() noexcept {

return (*mtEngine64)();

}

unsigned int  GetRand0Integer() noexcept {

return (*rand0Engine)();

}

auto GetRanlux48Integer() noexcept ->decltype(auto) {

return (*ranlux48Engine)();

}

private:

Random() noexcept {

mtEngine = std::make_shared(rd());

mtEngine64 = std::make_shared(rd());

dist = std::make_shared>(std::uniform_int_distribution< unsigned int >(0, maxRand));

rand0Engine = make_shared(rd());

ranlux48Engine = make_shared(rd());

}

std::random_device rd;

std::shared_ptr mtEngine;//32-bit Mersenne Twister by Matsumoto and Nishimura, 1998

std::shared_ptr mtEngine64; //64-bit Mersenne Twister by Matsumoto and Nishimura, 2000(马特赛特旋转演算法)

std::shared_ptr rand0Engine;

std::shared_ptr ranlux48Engine;

std::shared_ptr > dist;

};

int main()

{

cout << Random::getInstance().GetMTEngineInteger() << endl;

cout << Random::getInstance().GetMTEngine64Integer() << endl;

cout << Random::getInstance().GetRand0Integer() << endl;

cout << Random::getInstance().GetRanlux48Integer() << endl;

cout << Random::getInstance().getInteger() << endl;

return 0;

}

关于“c++如何产生随机数”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,使各位可以学到更多知识,如果觉得文章不错,请把它分享出去让更多的人看到。


当前标题:c++如何产生随机数
本文路径:http://cxhlcq.com/article/ieshss.html

其他资讯

在线咨询

微信咨询

电话咨询

028-86922220(工作日)

18980820575(7×24)

提交需求

返回顶部