srand使用非常量参数时不生效,randint始终返回相同值如何解决?
问题成因
- 该问题的核心是混用了两套互不关联的随机数生成体系:
srand()是C标准库<cstdlib>中为rand()函数配置随机种子的接口,仅能控制rand()生成的随机序列<experimental/random>头文件提供的std::experimental::randint()使用独立的内置随机数引擎,和rand()的种子、运行状态完全无关,调用srand()不会对它的输出产生任何影响
- 你观察到传入固定常量给
srand()时“运行正常”属于巧合,本质上无论如何调整srand()的入参,只要没有主动设置randint配套的随机种子,每次程序运行时randint都会基于默认固定种子输出相同的序列。
修复方案
可选两种修复方案,按需选择即可:
方案1:继续使用randint,正确配置对应种子
std::experimental随机库配套的种子设置接口为std::experimental::reseed(),将原代码中的srand调用替换为该接口即可:
#include <iostream> #include <experimental/random> #include <ctime> using namespace std; int main() { experimental::reseed(time(nullptr)); for (int i = 0; i < 4; ++i) { int random = experimental::randint(0, 9); cout << random; } return 0; }
方案2:改用C标准库rand()生成随机数
如果要继续使用srand()管理种子,将随机数生成逻辑替换为rand()即可,生成[0,9]区间数值的写法为rand() % 10:
#include <iostream> #include <cstdlib> #include <ctime> using namespace std; int main() { srand(time(nullptr)); for (int i = 0; i < 4; ++i) { int random = rand() % 10; cout << random; } return 0; }
补充说明:
time()函数的精度为秒,如果程序在1秒内多次启动,会因为获取到相同的时间戳生成相同的随机序列,对种子随机性要求更高的场景可以改用<chrono>库的高分辨率时钟生成种子。
内容的提问来源于stack exchange,提问作者RETOVSKEJ
相关产品推荐
相关产品推荐

