What is the best way to generate random numbers in C++?(在 C++ 中生成随机数的最佳方法是什么?)
问题描述
生成随机数的最佳方法是什么?
What is the best way to generate random numbers?
推荐答案
当且仅当:
您不是在寻找完美的一致性"或
您没有 C++11 支持,甚至没有 TR1(因此您别无选择)
那么您可能会考虑使用以下 C 风格的解决方案,其中(为了这个社区的声誉~请参阅 rand() 被认为有害) 以删除线字体书写:
then you might consider using the following C-style solution, which (for the sake of the reputation of this community ~ see rand() Considered Harmful) is written in strike-through font:
这是一个简单的 C 风格的函数,它从 min
到 max
的区间生成随机数,包括.这些数字似乎非常接近均匀分布.
Here's the simple C-style function that generates random number from the interval from min
to max
, inclusive. Those numbers seem to be very close to being uniformly distributed.
int irand(int min, int max) {
return ((double)rand() / ((double)RAND_MAX + 1.0)) * (max - min + 1) + min;
}
并且在使用之前不要忘记调用srand
:
int occurences[8] = {0};
srand(time(0));
for (int i = 0; i < 100000; ++i)
++occurences[irand(1,7)];
for (int i = 1; i <= 7; ++i)
printf("%d ", occurences[i]);
输出:14253 14481 14210 14029 14289 14503 14235
还可以看看:
生成范围内的随机数?
在整个范围内均匀生成随机数
找些时间,至少观看上述 视频的前 11 分钟一个>
使用
只是就像 Kerrek SB 已经指出的那样.
use <random>
just like it was pointed out by Kerrek SB already.
这篇关于在 C++ 中生成随机数的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 C++ 中生成随机数的最佳方法是什么?


- C++ 协变模板 2021-01-01
- 与 int by int 相比,为什么执行 float by float 矩阵乘法更快? 2021-01-01
- 从python回调到c++的选项 2022-11-16
- 如何对自定义类的向量使用std::find()? 2022-11-07
- 静态初始化顺序失败 2022-01-01
- Stroustrup 的 Simple_window.h 2022-01-01
- STL 中有 dereference_iterator 吗? 2022-01-01
- 近似搜索的工作原理 2021-01-01
- 一起使用 MPI 和 OpenCV 时出现分段错误 2022-01-01
- 使用/clr 时出现 LNK2022 错误 2022-01-01