c - srand 与 rand 函数有什么关系?

标签 c random srand

我了解到,如果您不更改种子编号,则 rand() 函数会在您每次运行时生成相同的编号。这就是 srand() 发挥作用的地方。时间总是在变化,所以我知道您应该将 time(null) 参数传递给 srand。我的问题是来自教程站点的以下代码。

int main()
{
    int i, n=5;
    time_t t;

    /* Intializes random number generator */
    srand((unsigned) time(&t));

    /* Print 5 random numbers from 0 to 50 */
    for( i = 0 ; i < n ; i++ ) {
        printf("%d\n", rand() % 50);
    }

    return(0);
}

我没有看到来自 srand 的链接

((unsigned) time(&t)); 

和兰特。

printf("%d\n", rand() % 50);

rand和srand的联系在哪里?我的意思或期望是我假设 rand() 将从 srand() 获取一些参数,因此它知道每次生成不同的数字。我假设它看起来像 rand(srand(time(null));

这就像初始化一个变量而不使用它对我来说。 srand 正在初始化,但我没有看到它被使用。

rand 是否会生成不同的数字,因为 srand 在 rand 之前先被调用?

最佳答案

随机数种子是一个全局静态变量。 randsrand 都可以访问它。

关于c - srand 与 rand 函数有什么关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21273550/

相关文章:

c++ - 检测按键按下和按键释放事件

c# - 随机化字符串中的字符列表,C#

c++ - 如何检测整个周期的C++随机引擎已经被消耗

c - C 中的 srand - 只需重复一次

c++ - 在 C++ 中使用 srand() 的测试用例的新值集

c - C中使用堆栈的post_order遍历

c - 发生写访问冲突

C++ srand,DLL 中的 rand 奇怪行为

c - 为什么在 C 的宏中使用循环而不是 block

python 2 vs python 3 随机性能,特别是 `random.sample` 和 `random.shuffle`