문제

I am using the below code to select a random short between 0 and 4000:

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

However, I am getting the value 24,583 returned?

도움이 되었습니까?

해결책

You'll want to change your code to:

std::uniform_int_distribution<unsigned short> dist(0, 4000);

The std::uniform_real_distribution you currently use expects to be used with floating point types only.


Now as for the standard because I like to quote!

In Standard(N3797) 26.5.2 [rand.synopsis] one of the items is the declaration for the std::uniform_real_distribution:

// 26.5.8.2.2, class template uniform_real_distribution
template<class RealType = double>
class uniform_real_distribution;

which links us to 26.5.8.2.2 for more information, but the important thing is in the declaration already. The templated type is named RealType and under

Standard 26.5.1.1 rand.req.genl]/1

Throughout this subclause 26.5, the effect of instantiating a template:

... d) that has a template type parameter named RealType is undefined unless the corresponding template argument is cv-unqualified and is one of float, double, or long double.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top