随机数生成器min和max-bound,不工作?

use*_*112 1 c++ random c++11

我使用下面的代码来选择0到4000之间的随机短消息:

std::random_device rd;
std::mt19937 mt(rd());
std::uniform_real_distribution<unsigned short> dist(0, 4000);
unsigned short random_no = dist(mt);
Run Code Online (Sandbox Code Playgroud)

但是,我得到的值是24,583?

use*_*027 6

您需要将代码更改为:

std::uniform_int_distribution<unsigned short> dist(0, 4000);
Run Code Online (Sandbox Code Playgroud)

std::uniform_real_distribution您目前使用的预计只有浮点类型使用.


现在至于标准,因为我想引用!

在标准(N3797)26.5.2中,[rand.synopsis]其中一项是以下声明std::uniform_real_distribution:

// 26.5.8.2.2, class template uniform_real_distribution
template<class RealType = double>
class uniform_real_distribution;
Run Code Online (Sandbox Code Playgroud)

它将我们链接到26.5.8.2.2以获取更多信息,但重要的是已在声明中.该模板类型命名为RealType

标准26.5.1.1 rand.req.genl]/ 1

在本子条款26.5中,实例化模板的效果:

... d)具有名为RealType的模板类型参数是未定义的,除非相应的模板参数是cv-unqualified并且是float,double或long double之一.