C++中推荐使用<random>库生成随机数,它比传统rand()函数更安全、分布更均匀。1. 使用std::random_device初始化种子;2. 选用std::mt19937作为随机数引擎;3. 配合std::uniform_int_distribution或std::uniform_real_distribution生成指定范围的整数或浮点数。

在C++中生成随机数,常用的方法是结合标准库中的 <random> 头文件。相比传统的 rand() 函数,现代C++推荐使用更精确、分布更均匀的随机数生成方式。
C++11 引入了 <random> 头文件,提供了更强大和灵活的随机数工具。主要由两部分组成:随机数引擎(如 std::mt19937)和分布类型(如 std::uniform_int_distribution)。
示例代码:
#include <iostream>
#include <random>
int main() {
std::random_device rd; // 获取真随机种子
std::mt19937 gen(rd()); // 随机数引擎
std::uniform_int_distribution<int> dis(1, 100); // 范围 [1, 100]
for (int i = 0; i < 5; ++i) {
std::cout << dis(gen) << " ";
}
return 0;
}
在较老的C++代码中,常使用 rand() 和 srand() 来生成随机数。这种方法简单但不推荐用于需要高质量随机性的场景。
立即学习“C++免费学习笔记(深入)”;
示例代码:
#include <iostream>
#include <cstdlib>
#include <ctime>
int main() {
srand(time(0)); // 设置种子
for (int i = 0; i < 5; ++i) {
std::cout << (rand() % 100 + 1) << " "; // 生成 1~100 的数
}
return 0;
}
如果需要生成随机浮点数,可以使用 std::uniform_real_distribution。
示例:
std::uniform_real_distribution<double> dis(0.0, 1.0); std::cout << dis(gen) << std::endl; // 输出 [0.0, 1.0) 之间的浮点数
基本上就这些。推荐优先使用 <random> 库,它更安全、更灵活,能避免 rand() 带来的分布不均和可预测性问题。
以上就是C++如何生成随机数_C++ 随机数生成方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号