简体   繁体   English

我们在C中使用时间(NULL)来生成=随机值

[英]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.

相关问题 每当我们在Visual Studio 2017中使用C语言运行程序时,如何生成一组不同的随机值? - How to generate a different set of random values every time we run a program in C language in visual studio 2017? C中的时间(NULL)是什么? - What is time(NULL) in C? 我想在C中生成随机值 - I would like to to generate random values in C 我应该使用什么样的哈希来从一组字符串中生成随机值 - what hashing should i use to generate random values from a set of strings 如果我没有 time.h 库来执行 srand,如何在 cooja(c 代码)中生成随机浮点值 - How to generate a random float values in cooja (c code) if I don't have time.h library to perform srand 如何在C中使用rand()在不带time.h的情况下生成随机数 - How to generate random numbers with rand() without time.h in C 如何在设定范围内以均匀的间隔在c中生成随机值 - how to generate random values with uniform intervals in c within a set range 什么是C库函数生成随机字符串? - What's the C library function to generate random string? 用c生成随机ip数最快的方法是什么? - what is the fastest way to generate random ip numbers in c? 使用pthread在C中生成随机数的最正确方法是什么 - What is the most correct way to generate random numbers in C with pthread
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM