为什么我的C随机数发生器只返回"42"?

Rav*_*mer 2 c linux random

由于这是一个令人敬畏的意外特征,它使得"洗牌"一系列"卡片"变得糟糕.我得到相同数字的事实告诉我,每次采摘单独的种子时我都遇到了一些问题.我使用srand48time(NULL)拨打电话不正确吗?我缺少一些潜在的逻辑漏洞吗?在迭代之间没有足够的时间来使值time()不同吗?

代码正在Linux上运行.

void shuffle()

{
  int i_rnd;   /* Integer random number, range 0..100 */
  int i_rnd2;
  card tempCard; /*temporary card to facillitate swapping*/
  int i = 0; /*can't use a FOR loop 'cause we're not using c99 standard*/
  while(i < 1000)
  {

      srand48( (unsigned) time( NULL ) );  /* Seed the random number generator */
      i_rnd = (int) ( drand48() * 100);
      i_rnd = i_rnd%52; // return a random number 0-51    
      i_rnd2 = (int) ( drand48() * 100);
      i_rnd2 = i_rnd2%52; // return a random number 0-51
      /*we have two random numbers, now exchange the two objects with the
      / picked array indices */
      tempCard =  cardDeck[i_rnd];
      cardDeck[i_rnd]=cardDeck[i_rnd2];
      cardDeck[i_rnd2]=tempCard;
      //swap complete. increment counter so we can eventually get out of the while
      i++;

  }

return;

}
Run Code Online (Sandbox Code Playgroud)

Jam*_*lis 14

您需要为伪随机数生成器播种一次,而不是每次使用它.

在给定某个种子值的情况下,许多(大多数?)伪随机数生成器(PRNG)是确定性的.如果time()每次循环执行时返回相同的值,则每次使用PRNG时都会使用相同的值,因此当您查询它以获取随机数时,它将返回相同的值.

  • @Raven:最好在`main()`或从`main()`调用的函数中播种PRNG.您希望每次运行程序时都准确播种一次. (5认同)
  • @Raven:不,把它移到你的`main()`.每次洗牌都不想播种. (2认同)

Fre*_*son 5

因为你每次通过循环使用相同的种子播种你的随机数生成器(它在不到一秒的时间内运行).srand48()在程序开头调用ONCE.