当你在函数内部调用srand()时,它是否只在该函数内部种子rand()?
int main(){ srand(static_cast<unsigned int>(time(0))); random_number(); } void random_number(){ rand(); }
使用rand()的函数random_number位于调用srand()的位置之外.
所以我的问题是 – 如果你使用srand()种子rand(),你可以在调用srand()的地方之外使用种子rand()吗?包括功能,不同文件等
解决方法
srand实际上是全局的,我们可以看到这一点到
draft C99 standard,我们可以参考C标准,因为C回到C库函数的C标准,它说(强调我的):
The srand function uses the argument as a seed for a new sequence of pseudo-random
numbers to be returned by subsequent calls to rand. If srand is then called with the
same seed value,the sequence of pseudo-random numbers shall be repeated. If rand is
called before any calls to srand have been made,the same sequence shall be generated
as when srand is first called with a seed value of 1.
它不会将其影响限制在它所使用的范围内,它只是说它影响后续调用rand
标准草案中提供的可移植实现的示例使得更明确的是效果是全局的:
static unsigned long int next = 1; void srand(unsigned int seed) { next = seed; }