Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
428 views
in Technique[技术] by (71.8m points)

c - How does srand relate to rand function?

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);
}

I see no link from the srand

((unsigned) time(&t)); 

and rand.

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

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));

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...