[英]How to generate a different set of random values every time we run a program in C language in visual studio 2017?
srand( (unsigned)time(null))
is not working though I have include stdlib.h
library too. 尽管我也包含了stdlib.h
库,但srand( (unsigned)time(null))
无法正常工作。 It says time
is an undefined word as an error. 它说time
是一个错误的未定义词。
int i, max = 16, a[16];
for (i = 0; i < 16; i++)
a[i] = i;
srand((unsigned) time_t( NULL));
for (int i = 0; i < 16; i++) { // shuffle array
int temp = a[i];
int randomIndex = rand() % max;
a[i] = a[randomIndex];
a[randomIndex] = temp;
}
time_t
is the type, not the function. time_t
是类型,而不是函数。 You still call time
. 你仍然可以调用time
。 "Calling" time_t( NULL )
is constructing a time_t
with a value of 0
, so of course you get the same random stream every time. “调用” time_t( NULL )
正在构造一个time_t
,其值为0
,因此当然您每次都会获得相同的随机流。
As the other answer notes, you need to #include <time.h>
, but you also need to call time
properly; 如其他答案所述,您需要#include <time.h>
,但是您还需要正确地调用time
。 your use of time_t
here is equivalent to always seeding with zero. 您在此处使用time_t
等于始终以零进行播种。 You need to change your seeding to: 您需要将播种更改为:
srand((unsigned)time(NULL));
which will return the current time as a time_t
which you then cast to unsigned
for use as the seed. 它将返回当前时间为time_t
,然后将其转换为unsigned
用作种子。
time()
函数位于time.h中 ,而不是stdlib.h中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.