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++ 中生成随机数的最佳方法是什么?


基础教程推荐
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 我有静态或动态 boost 库吗? 2021-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 常量变量在标题中不起作用 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- C++结构和函数声明。为什么它不能编译? 2022-11-07
- 在 C++ 中计算滚动/移动平均值 2021-01-01