简体   繁体   中英

How to generate different random numbers in one single runtime?

Consider this code:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
  int ctr;
  for(ctr=0;ctr<=10;ctr++)
    {
      int iSecret;
      srand ( time(NULL) );
      printf("%d\n",iSecret = rand() % 1000 + 1);
    }
}

And it outputs this: 256 256 256 256 256 256 256 256 256 256

Unfortunately, I want the output to print 10 different random numbers in that loop.

Move the call to srand(time(NULL)); to before the for loop.

The problem is that time() changes only once in every second, but you're generating 10 numbers, and unless you have an extremely slow CPU, it won't take a second to generate those 10 random numbers.

So you're re-seeding the generator with the same value each time, making it return the same number.

Put srand ( time(NULL) ); before the loop. Your loop probably runs within a second so you are reinitialising the seed with the same value.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
  int ctr;
  srand ( time(NULL) );
  for(ctr=0;ctr<=10;ctr++)
    {
      int iSecret;
      printf("%d\n",iSecret = rand() % 1000 + 1);
    }
}

keep srand(time(0)) outside of the for loop. it should not be inside that loop.

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
  int ctr;
  srand ( time(NULL) );
  for(ctr=0;ctr<=10;ctr++)
    {
      int iSecret;
      printf("%d\n",iSecret = rand() % 1000 + 1);
    }
}

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