且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我的 srand(time(NULL)) 函数每次在 c 中生成相同的数字?

更新时间:2023-02-03 12:15:49

原因是 time(NULL) 每秒只改变一次!这意味着,您使用 相同 种子为随机数生成器播种 100 次.更好的方法是在流程开始时只为 RNG 设置一次种子(在 main() 的开头,然后你应该得到不同的值.

The reason is, that time(NULL) changes only once per second! This means, that you seed the random number generator 100 times with the same seed. A better way is to seed the RNG only once at start of the process (at the head of main(), then you should get different values.

如果您启动程序的频率超过一秒一次,您也可以使用

If you start your program more often than once a second, you could also seed it with

srand(time(NULL)+getpid());

或类似的.