cpp random number in range
To generate a random number in a specific range using C++, you can use the <random>
library. Here are the steps to follow:
Include the
<random>
library: Start by including the<random>
library at the beginning of your code. This library provides a set of functions and classes for generating random numbers.Create a random number generator object: Next, create an instance of a random number generator. This can be done by declaring a variable of type
std::random_device
orstd::mt19937
, which are commonly used random number generator types.Set the seed for the random number generator: To ensure that the random numbers generated are different each time the program runs, you need to set a seed for the random number generator. You can do this by calling the
seed
method of the random number generator object and passing it a value. Commonly used values for the seed include the current time or a combination of system-specific information.Create a distribution object for the desired range: Now, create a distribution object that represents the range of random numbers you want to generate. The distribution object is created by declaring a variable of the desired distribution type, such as
std::uniform_int_distribution
for generating random integers within a range.Generate a random number: Finally, generate a random number by calling the
operator()
method of the distribution object and passing it the random number generator object as an argument. This will return a random number within the specified range.
Here's an example that puts all these steps together to generate a random number between 1 and 100:
#include <iostream>
#include <random>
int main() {
std::random_device rd;
std::mt19937 generator(rd());
std::uniform_int_distribution<int> distribution(1, 100);
int randomNumber = distribution(generator);
std::cout << "Random number: " << randomNumber << std::endl;
return 0;
}
In this example, the std::random_device
is used as the random number generator, and the std::uniform_int_distribution
is used to generate random integers within the range [1, 100]. The generated random number is then printed to the console.