📅  最后修改于: 2023-12-03 15:13:54.801000             🧑  作者: Mango
In C++, the random
library provides functionality for generating pseudo-random numbers. Random numbers are widely used in computer programs for various purposes including simulations, cryptography, and game development. C++ provides a rich set of functions and classes to generate random numbers and manipulate them as needed.
The random
library in C++ offers the following features:
To generate random numbers in C++, you can use the random_device
class to obtain a seed and then use it to initialize a random number generator object. Here's an example:
#include <random>
#include <iostream>
int main() {
std::random_device rd; // obtain a random seed from the operating system
std::mt19937 gen(rd()); // initialize the random number generator
std::uniform_int_distribution<> dist(1, 100); // define the range
// generate and print random numbers
for (int i = 0; i < 10; ++i) {
int random_num = dist(gen);
std::cout << random_num << " ";
}
return 0;
}
The above code generates 10 random numbers between 1 and 100, inclusive.
To generate random floating-point numbers, you can use the uniform_real_distribution
class instead of uniform_int_distribution
. Here's an example:
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_real_distribution<> dist(0, 1);
// generate and print random floating-point numbers
for (int i = 0; i < 5; ++i) {
double random_num = dist(gen);
std::cout << random_num << " ";
}
return 0;
}
The above code generates 5 random floating-point numbers between 0 and 1.
To generate random boolean values, you can use the bernoulli_distribution
class. It produces true
or false
values based on a specified probability. Here's an example:
#include <random>
#include <iostream>
int main() {
std::random_device rd;
std::mt19937 gen(rd());
std::bernoulli_distribution dist(0.5); // 50% chance of true
// generate and print random boolean values
for (int i = 0; i < 5; ++i) {
bool random_bool = dist(gen);
std::cout << std::boolalpha << random_bool << " ";
}
return 0;
}
The above code generates 5 random boolean values with a 50% chance of being true
.
The random
library in C++ provides powerful features for generating and manipulating random numbers. From generating random numbers within a specified range to shuffling and selecting elements randomly, these features are essential for many programming tasks. Utilizing the random
library effectively can make your programs more dynamic and realistic.