C++产生随机数的几种方法小结

本文主要介绍了C++产生随机数的几种方法小结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧

使用cstdlib库

C++11之前,C和C++都用相同的方法来产生随机数(伪随机数),即rand()函数,用法如下:

1)使用srand()撒一个种子

功能:初始化随机数发生器

用法:void srand(unsigned int seed)

2)使用rand()产生随机数

功能:随机数发生器

用法:int rand(void)

3)控制随机数范围

要取得 [a,b) 的随机整数,使用 (rand() % (b-a))+ a;

要取得 [a,b] 的随机整数,使用 (rand() % (b-a+1))+ a;

要取得 (a,b] 的随机整数,使用 (rand() % (b-a))+ a + 1;

** 参考:C++ rand 与 srand 的用法

4)示例代码

#include  #include  #include  int getRand(int min, int max); int main() { srand(time(0)); for (int i=0; i<10; i++) { int r = getRand(2,20); std::cout << r << std::endl; } return 0; } // 左闭右闭区间 int getRand(int min, int max) { return ( rand() % (max - min + 1) ) + min ; }

使用random库:c++11 random library

C++11之前,无论是C,还是C++都使用相同方式的来生成随机数,而在C++11中提供了随机数库,包括随机数引擎类、随机数分布类,简介如下:

随机数引擎类

一般使用 default_random_engine 类,产生随机非负数(不推荐直接使用)

直接使用时:

#include  #include  #include  int main() { std::default_random_engine e; e.seed(time(0)); for (int i=0; i<10; i++) { std::cout << e() << std::endl; } return 0; }

输出结果:

16807
282475249
1622650073
984943658
1144108930
470211272
101027544
1457850878
1458777923
2007237709

随机数分布类

uniform_int_distribution:产生均匀分布的整数

示例代码:

#include  #include  #include  int main() { std::default_random_engine e; std::uniform_int_distribution u(2,20); // 左闭右闭区间 e.seed(time(0)); for (int i=0; i<10; i++) { std::cout << u(e) << std::endl; } return 0; }

输出结果:

4
5
16
17
15
17
6
10
13
13

uniform_real_distribution:产生均匀分布的实数

#include  #include  #include  int main() { std::default_random_engine e; std::uniform_real_distribution u(1.5,19.5); // 左闭右闭区间 e.seed(time(0)); for (int i=0; i<10; i++) { std::cout << u(e) << std::endl; } return 0; }

输出结果:

11.9673
2.29179
9.82668
9.82764
10.2394
13.8324
2.95336
9.72177
16.5145
12.1421

normal_distribution:产生正态分布的实数

示例代码:

#include  #include  #include  int main() { std::default_random_engine e; std::normal_distribution u(0,1); // 均值为0,标准差为1 e.seed(time(0)); for (int i=0; i<10; i++) { std::cout << u(e) << std::endl; } return 0; }

输出结果:

0.390995
-0.680137
-1.02953
-0.53243
0.375886
-0.19804
-0.796159
0.837714
0.899632
2.06609

bernoulli_distribution:生成二项分布的布尔值

#include  #include  #include  int main() { std::default_random_engine e; std::bernoulli_distribution u(0.8); // 生成1的概率为0.8 e.seed(time(0)); for (int i=0; i<10; i++) { std::cout << u(e) << std::endl; } return 0; }

输出结果:

1
0
1
1
1
1
1
1
1
1

参考:C++11新特性(75)-随机数库(Random Number Library)

到此这篇关于C++产生随机数的几种方法小结的文章就介绍到这了,更多相关C++产生随机数内容请搜索0133技术站以前的文章或继续浏览下面的相关文章希望大家以后多多支持0133技术站!

以上就是C++产生随机数的几种方法小结的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » C语言