[英]How to generate a different set of random values every time we run a program in C language in visual studio 2017?
尽管我也包含了stdlib.h
库,但srand( (unsigned)time(null))
无法正常工作。 它说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
是类型,而不是函数。 你仍然可以调用time
。 “调用” time_t( NULL )
正在构造一个time_t
,其值为0
,因此当然您每次都会获得相同的随机流。
如其他答案所述,您需要#include <time.h>
,但是您还需要正确地调用time
。 您在此处使用time_t
等于始终以零进行播种。 您需要将播种更改为:
srand((unsigned)time(NULL));
它将返回当前时间为time_t
,然后将其转换为unsigned
用作种子。
time()
函数位于time.h中 ,而不是stdlib.h中 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.