What are the methods for generating random numbers in C++?
In C++, there are several methods available for generating random numbers:
- By using the standard library function rand(), you can generate pseudo-random numbers. You need to first set a random number seed using the srand() function, which can be done by using the time() function to get the current time as the seed, and then call the rand() function to generate random numbers.
Example code:
#include <cstdlib>
#include <ctime>
#include <iostream>
int main() {
// 设置随机数种子
srand(time(0));
// 生成随机数
int randomNumber = rand();
// 输出随机数
std::cout << "Random number: " << randomNumber << std::endl;
return 0;
}
- The random number library in C++11: C++11 introduced a new random number library that offers higher quality random number generators and more random distribution functions. You can use std::random_device as a seed, then use std::mt19937 as the random number engine, along with different distribution functions to generate different types of random numbers.
Sample code:
#include <random>
#include <iostream>
int main() {
// 设置随机数引擎和分布函数
std::random_device rd;
std::mt19937 gen(rd());
std::uniform_int_distribution<int> dis(1, 6);
// 生成随机数
int randomNumber = dis(gen);
// 输出随机数
std::cout << "Random number: " << randomNumber << std::endl;
return 0;
}
The above are two commonly used methods to generate random numbers in C++, you can choose the one that suits your needs based on actual requirements.