gpt4 book ai didi

C++ 如何阻止随机引擎产生负数?

转载 作者:行者123 更新时间:2023-12-03 06:56:01 26 4
gpt4 key购买 nike

我有一个函数试图生成 18 到 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 之间的数字?

最佳答案

您正在使用 std::normal_distribution,它根据正态(或高斯)随机数分布生成随机数。您正在使用 this构造函数:

explicit normal_distribution( RealType mean, RealType stddev = 1.0 );

你想要的是std::uniform_real_distribution。查看reference :

Produces random floating-point values i, uniformly distributed on the interval [a, b)

请注意,您的引擎和分布必须是thread_local(或static)并且随机设备可以是临时的。否则你的结果不会均匀分布。您还应该考虑获取一个随机整数而不是 double 整数,因为无论如何返回类型都是 int:

#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++ 如何阻止随机引擎产生负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64532780/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com