在C++中,可以使用以下几种方法生成随机数:
示例代码:
#include <cstdlib>
#include <ctime>
#include <iostream>
int main() {
    // 设置随机数种子
    srand(time(0));
    
    // 生成随机数
    int randomNumber = rand();
    
    // 输出随机数
    std::cout << "Random number: " << randomNumber << std::endl;
    return 0;
}
示例代码:
#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;
}
以上是C++中生成随机数的两种常用方法,可以根据实际需求选择适合的方法。