srand 与 rand 函数有什么关系? [英] How does srand relate to rand function?

查看:31
本文介绍了srand 与 rand 函数有什么关系?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I understand that rand() function generates the same number(s) each you run it if you don't change the seed number. That's where srand() comes in. Time is always changing so I know that you should pass the time(null) parameter to srand. My question is with the code below from a tutorial site.

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
", rand() % 50);
    }

    return(0);
}

我没有看到来自 srand 的链接

I see no link from the srand

((unsigned) time(&t)); 

和兰特.

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

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

Where is the connection between rand and srand? What I mean or expect is I assume rand() will get some parameter from srand() so it knows to generate different numbers each time. I assume it would look something like rand(srand(time(null));

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

It's like initializing a variable without using it to me. srand is being initialized, but I don't see it being used.

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

Does rand generate different numbers because srand is called first before rand?

推荐答案

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

The random number seed is a global static variable. rand and srand both have access to it.

这篇关于srand 与 rand 函数有什么关系?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆