C++ 如何阻止随机引擎产生负数? [英] C++ how to stop a random engine from producing negative numbers?
问题描述
我有一个函数试图生成 18 到 5 之间的随机数
I have a function that im trying to produce random numbers between 18 and 5
int randomAge() {
int random;
std::random_device rd;
static std::default_random_engine generator(rd()); //produce a static random engine
std::normal_distribution<double> distribution(18, 52); //random age between 18 and 52
random = distribution(generator);
return random;
}
但是,我收到了大于 52 的负数和偶数.我该如何解决这个问题,使其生成 18 到 52 之间的数字?
However I am recieving negative numbers and even numbers that are higher than 52. How can I fix this so it produces numbers between 18 and 52?
推荐答案
您正在使用 std::normal_distribution
,它根据正态(或高斯)随机数分布生成随机数.您正在使用 this 构造函数:
You're using std::normal_distribution
which generates random numbers according to the Normal (or Gaussian) random number distribution. You're using this constructor:
explicit normal_distribution( RealType mean, RealType stddev = 1.0 );
你想要的是std::uniform_real_distribution
.请参阅参考:
产生随机浮点值 i,均匀分布在区间 [a, b)
Produces random floating-point values i, uniformly distributed on the interval [a, b)
请注意,您的引擎和发行版必须是 thread_local
(或 static
),并且随机设备可以是临时的.否则,您的结果分布不均匀.您还应该考虑获取一个随机整数而不是 double,因为无论如何返回类型都是 int
:
Do note that your engine and distribution must be thread_local
(or static
) and the random device can be a temporary. Otherwise your results are not uniformly distributed. You should also consider getting a random integer instead of double since the return type is int
anyway:
#include <random>
int randomAge() {
thread_local std::mt19937 engine{ std::random_device{}() };
thread_local std::uniform_int_distribution<int> distribution{ 18, 52 };
return distribution(engine);
}
相关:
这篇关于C++ 如何阻止随机引擎产生负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!