c++ - srand()的含义

标签 c++ c random srand time.h

我不明白 srand() 的含义在<time.h>创建一个随机数。 这是我的代码:

/* srand example */
#include <stdio.h>      /* printf, NULL */
#include <stdlib.h>     /* srand, rand */
#include <time.h>       /* time */

int main ()
{
  printf ("First number: %d\n", rand()%100);
  srand (time(NULL));
  printf ("Random number: %d\n", rand()%100);
  srand (1);
  printf ("Again the first number: %d\n", rand()%100);

  return 0;
}

结果是:

First number: 41
Random number: 13
Again the first number: 41

为什么结果是srand(1)不同于srand(2) ? 为什么srand(1)的结果是或srand(2)不断出现? 为什么我必须使用 srand(time(NULL))为了创建动态随机数?

最佳答案

如果你看docs :

Seeds the pseudo-random number generator used by std::rand() with the value seed.

rand() 有一些内部状态,它从一次调用到下一次调用都保留着这些状态。该函数是确定性的 - 但我们可以将其输出视为伪随机的。因此产生的值(value):

srand(1);
rand();
对于给定的实现,

将始终相同。这就是为什么注释指出:

Generally speaking, the pseudo-random number generator should only be seeded once, before any calls to rand(), and the start of the program. It should not be repeatedly seeded, or reseeded every time you wish to generate a new batch of pseudo-random numbers.

关于c++ - srand()的含义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28305016/

相关文章:

c++ - 重载函数以同时获取指针或引用是不好的做法吗?

无法写入 dsPIC30F OSCCON

c - 套接字读/写错误

android - Andengine,让 Sprite 随机 move

c - 使用循环在数组中生成唯一随机数

javascript - 将随机背景图像更改为另一个随机背景(使用淡入淡出过渡)

c++ - 为什么这个模板代码可以编译?

c++ - Mac(或 C++)连接到二进制 WCF

c++ - CAN 套接字读取帧延迟

创建一个 GUI 来绘制 Linux 中的 CPU 使用率