You seek a method to uniformly generate random numbers within a specified range [min, max].
Flaws with rand
Your current implementation using rand() and the modulus operator may not ensure uniform distribution, as its behavior depends on RAND_MAX and the range itself.
C 11 and Uniform Range Generation
In C 11, std::uniform_int_distribution offers a solution tailored to this need:
#include <random> std::uniform_int_distribution<int> distr(min, max); std::random_device rand_dev; std::mt19937 generator(rand_dev()); int random_number = distr(generator);
Additional Features of
The
Container Shuffling
To shuffle a container, employ std::shuffle:
#include <random> #include <vector> std::vector<int> vec = {4, 8, 15, 16, 23, 42}; std::random_device random_dev; std::mt19937 generator(random_dev()); std::shuffle(vec.begin(), vec.end(), generator);
Boost.Random
If using a C 11 compiler is not feasible, consider Boost.Random, which features a similar interface to the C 11 counterpart.
The above is the detailed content of How Can I Generate Uniformly Distributed Random Numbers Within a Specific Range in C ?. For more information, please follow other related articles on the PHP Chinese website!