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++ 中生成随机数的最佳方法是什么?
基础教程推荐
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- CString 到 char* 2021-01-01
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
