简体   繁体   中英

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. It says time is an undefined word as an error.

  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. You still call 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.

As the other answer notes, you need to #include <time.h> , but you also need to call time properly; your use of time_t here is equivalent to always seeding with zero. 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()函数位于time.h中 ,而不是stdlib.h中

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM