[英]For what we use time(NULL) in C to generate =random values
For what we use time(NULL) in C to generate random values? 我们在C中使用时间(NULL)来生成随机值? What is the meaning of time(NULL)
in this code? 这段代码中time(NULL)
的含义是什么?
int i, zarodek;
zarodek= time(NULL);
srand(zarodek);
int r = rand() % 49 + 1;
printf("%d",r);
It is getting the system time (in seconds). 它正在获得系统时间(以秒为单位)。 You may optionally supply a pointer to a time_t
value that will receive the time, but since the value is returned from the time
function anyway, you may pass NULL
instead (and the function will not attempt to assign to the null pointer). 您可以选择提供一个指向time_t
值的指针,该指针将接收时间,但由于该值始终从time
函数返回,因此您可以传递NULL
(并且该函数不会尝试分配给空指针)。
The purpose of using time
is to seed the random number generator (passing it to srand
). 使用time
的目的是为随机数生成器播种(将其传递给srand
)。 It's common to use the time, because it's generally different every time your program is run. 使用时间很常见,因为每次运行程序时它通常都不同。
Note, you should only seed once (not every time you call rand
). 请注意,您应该只播种一次(不是每次调用rand
)。
That is seeding the random number generator with the current time. 那就是用当前时间播种随机数发生器。 If you don't do this, then each time you run your program, you will get the same sequence of random numbers. 如果不这样做,那么每次运行程序时,都会得到相同的随机数序列。
Try it! 试试吧!
您可以按时间返回当前时间,也可以将指针传递给目标struct time_t
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.