c++ - 为什么使用rand生成随机数之前需要调用srand

标签 c++ c

需要在 srand(time(NULL)); 行上调用 srand 来设置 rand() 的种子来生成随机数。 我的问题是需要什么种子?

最佳答案

rand() 函数是一个伪随机数生成器,即

The rand() function returns a pseudo-random integer in the range 0 to RAND_MAX inclusive

伪随机数的生成取决于种子。如果您不提供不同的值作为种子,您将在应用程序的每次调用中获得相同随机数。这就是为什么,srand() 用于随机化种子本身。

最常见的做法:srand(time(NULL)) [适合单次运行评估]。

what is the need for the [explicit] seed ?

值得一提的是,来自man page

If no seed value is provided, the rand() function is automatically seeded with a value of 1.

关于c++ - 为什么使用rand生成随机数之前需要调用srand,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28330978/

相关文章:

C++ 断言 : the precedence of the expression in an assert macro

c++ - MFC 在对话框中找不到 GetDocument()

c++ - 在 UWP C++ 应用程序中获取 CreateFile() 设备路径的首选方法是什么?

c++ - CMFCCaptionMenuButton 替代品?

c - C编程中的定点算法

c - 打印括号对,得到段错误

c++ - 编译器何时内联 C++ 代码?

c - 函数声明不是原型(prototype)

c - 在二维数组中找到最大的簇

c - 数据对齐与网络编程