If I don't specify srand(), what seed does ran

2020-02-07 02:43发布

Here is the code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main(void)
{
    int r;
    int i;
    for (i = 0; i < 100; i++)
    {
        r = rand() % 100 + 1;
        printf("%d\n", r);
    }
    return 0;
}

I've been trying to random number but one day, I forgot to put srand() in, but the rand() function can still random a number (the same sequence).

The question is, what seed does it use if I don't specify it?

标签: c random srand
5条回答
欢心
2楼-- · 2020-02-07 03:04

If srand is not called, rand acts as if srand(1) has been called.

http://www.acm.uiuc.edu/webmonkeys/book/c_guide/2.13.html#rand

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-02-07 03:07

The man pages state the following:

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

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

查看更多
等我变得足够好
4楼-- · 2020-02-07 03:17

The C standard actually stipulates the behaviour documented in the other answers:

ISO/IEC 9899:2011 §7.22.2.2 The srand function

¶2 [...] If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.

查看更多
Juvenile、少年°
5楼-- · 2020-02-07 03:22

The srand() function sets its argument as the seed for a new sequence of pseudo-random integers to be returned by rand(). These sequences are repeatable by calling srand() with the same seed value.

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

查看更多
做自己的国王
6楼-- · 2020-02-07 03:28
If rand() is called before any calls to srand() are made, the same sequence shall 
be generated as when srand() is first called with a seed value of 1.

Ref:

http://pubs.opengroup.org/onlinepubs/009695399/functions/rand.html

查看更多
登录 后发表回答