How to write code for generating random numbers in C++?

The code for generating random numbers in C++ can be implemented using the random header file in the standard library and a random number engine. Here is a simple example code:

#include <iostream>
#include <random>

int main() {
    // 使用随机数引擎生成器生成随机数
    std::random_device rd;  // 获取一个随机数种子
    std::mt19937 gen(rd()); // 使用随机数种子初始化随机数引擎
    std::uniform_int_distribution<int> dis(1, 100); // 定义一个范围为1到100的均匀分布

    int random_num = dis(gen); // 生成随机数

    std::cout << "随机数: " << random_num << std::endl;

    return 0;
}

This sample code utilizes std::random_device to obtain a random seed, then initializes a random number engine with std::mt19937, and finally defines a uniform distribution with a range of 1 to 100 using std::uniform_int_distribution. A random number is generated by calling dis(gen).

广告
Closing in 10 seconds
bannerAds