避免重复种子生成使用srand()函数函数、种子、srand

2023-09-11 02:43:45 作者:余生各自安好

我有一个典型的情况下,我需要产生一批随机数。我使用了一个循环,产生在每次通过100随机数:

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<npasses; i++)
{
   srand(time(NULL)); //Initialize seed

   for(int j=0; j<100; j++)
      printf("%d ", rand()%10);

   printf("\n"); //New line after 100 numbers
}

现在,内环在少于一毫秒执行。其结果是,存在在值的时间()没有变化。此重新初始化所述种子(srand()函数),以相同的数值和我的随机数被反复..

Now, the inner loop executes in less than a millisecond. As a result, there is no change in the value of time(). This re-initializes the seed (srand()) to the same value and my random numbers are REPEATED..

任何人都可以提出一个解决方法/修复。

Can anyone suggest a workaround/fix.

推荐答案

设置种子一次,循环之前。

Set the seed once, before the loop.