避免重复种子生成使用srand()函数 [英] Avoiding Repeated seed generation using srand()

查看:231
本文介绍了避免重复种子生成使用srand()函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个典型的情况下,我需要产生一批随机数。我使用了一个循环,产生在每次通过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.

这篇关于避免重复种子生成使用srand()函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆