Avoiding Repeated seed generation using srand()

后端 未结 4 636
悲哀的现实
悲哀的现实 2021-01-27 07:06

I have a typical situation where I need to generate a batch of random numbers. I have used a loop which generates 100 random numbers on each pass:

for(int i=0; i         


        
相关标签:
4条回答
  • 2021-01-27 07:50

    Keep srand out:

    srand(time(NULL)); //Initialize seed
    for(int i=0; i<npasses; i++)
    {
       for(int j=0; j<100; j++)
          printf("%d ", rand()%10);
    
       printf("\n"); //New line after 100 numbers
    }
    
    0 讨论(0)
  • 2021-01-27 07:54

    try this

    srand(clock()); //Initialize seed
    
    0 讨论(0)
  • 2021-01-27 08:00

    You can use the random generator to generate a new seed.

    For example:

    srand((unsigned int)rand());
    

    And use srand(time(NULL)) only once before the loop. But as suggested in another answer, you might as well drop the whole srand inside the loop as well.

    0 讨论(0)
  • 2021-01-27 08:09

    Set the seed once, before the loop.

    0 讨论(0)
提交回复
热议问题