srand()如何工作?

fat*_*ati 1 c random srand

这是我的代码:

#include<stdio.h>
#include<stdlib.h>
#include <time.h>
int main(){
float m, n;
printf("Enter n, m:");
scanf("%f %f", &n, &m);
int l;
l=m-n;
int i;
for(i=0; i<4; i++){
    srand(time(NULL));
    double r=rand();
    r/=RAND_MAX;
    r*=l;
    r+=n;
    printf("%f ", r);
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

为什么它生成相同的数字?当我srand(time(NULL));在循环之前写字时,它产生不同的数字!为什么会这样?这个程序如何运作?

chu*_*ica 5

srand() 种子随机数序列.

srand函数使用该参数作为后续调用返回的新伪随机数序列的种子rand.如果srand随后使用相同的种子值调用,则应重复伪随机数序列.......C11dr§7.22.2.22

并且time()通常是相同的值 - 对于第二个 @kaylum

[编辑]

最好srand()只在代码中提前调用一次

int main(void) {
  srand((unsigned) time(NULL));
  ...
Run Code Online (Sandbox Code Playgroud)

或者,如果您每次都想要相同的序列,则根本不要调用srand()- 对调试很有用.

int main(void) {
  // If code is not debugging, then seed the random number generator.
  #ifdef NDEBUG
    srand((unsigned) time(NULL));
  #endif
  ...
Run Code Online (Sandbox Code Playgroud)