What is the implementation method of random numbers in C++?
There are several common ways to implement random numbers in C++.
- Using the rand function from the C standard library:
#include <cstdlib> // 包含rand函数所在的头文件
#include <ctime> // 包含time函数所在的头文件
int main() {
// 初始化随机数种子
srand(time(NULL));
// 生成随机数
int randomNum = rand();
return 0;
}
- Using the random number engine and distribution functions from the C++ standard library:
#include <random>
int main() {
std::random_device rd; // 获取一个随机数种子
std::mt19937 gen(rd()); // 使用随机数种子初始化随机数引擎
std::uniform_int_distribution<> dis(1, 100); // 定义一个均匀分布的整数分布函数,范围是1到100
int randomNum = dis(gen); // 生成随机数
return 0;
}
- Utilize a third-party library, such as the Boost library’s random number generator.
#include <boost/random/mersenne_twister.hpp>
#include <boost/random/uniform_int_distribution.hpp>
int main() {
boost::random::mt19937 gen; // 使用mt19937引擎
boost::random::uniform_int_distribution<> dis(1, 100); // 定义一个均匀分布的整数分布函数,范围是1到100
int randomNum = dis(gen); // 生成随机数
return 0;
}
These methods can all be used to generate random numbers, the choice of which method to use depends on the specific needs and use cases.