如何生成 0 到 10 之间的随机数?我可以得到这个随机数生成的样本吗?
最佳答案
1) 你不应该使用 rand()
,它分布不好,周期短等等......
2) 当 MaxValue % x != 0
时你不应该使用 %x
因为你弄乱了你的均匀分布(假设你不使用 rand()) ,例如32767 % 10 = 7
所以数字 0-7 更有可能得到
观看此视频了解更多信息:Going native 2013 - Stephan T. Lavavej - rand() Considered Harmful
你应该使用类似的东西:
#include <random>
std::random_device rdev;
std::mt19937 rgen(rdev());
std::uniform_int_distribution<int> idist(0,10); //(inclusive, inclusive)
我在我的代码中使用了这样的东西:
template <typename T>
T Math::randomFrom(const T min, const T max)
{
static std::random_device rdev;
static std::default_random_engine re(rdev());
typedef typename std::conditional<
std::is_floating_point<T>::value,
std::uniform_real_distribution<T>,
std::uniform_int_distribution<T>>::type dist_type;
dist_type uni(min, max);
return static_cast<T>(uni(re));
}
注意:该实现不是线程安全的,并且为每次调用构造一个分布。那是低效的。但您可以根据需要修改它。
关于c++ - 生成 0 到 10 之间的随机数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5743678/