【问题标题】:Why does my C random number generator only return "42"?为什么我的 C 随机数生成器只返回“42”?
【发布时间】:2011-02-04 01:34:57
【问题描述】:

尽管这是一个非常棒的意外功能,但它却是一种糟糕的方式来“洗牌”一系列“卡片”。我得到相同数字的事实告诉我,我每次采摘不同的种子时都遇到了一些问题。我是否不正确地使用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;

}

【问题讨论】:

  • 42 是生命、宇宙和一切的答案。
  • 该程序会为您提供 答案,而无需执行不必要的步骤。我希望我有一台像你这样的电脑。
  • @Mike 你把我打败了!
  • @Andrew Cooper 让我们说......“一个人必须走多少条路?”并称之为千年。

标签: c linux random


【解决方案1】:

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

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

【讨论】:

  • 啊。那我会把它移到while循环之外。这是有道理的。
  • @Raven:在main() 或从main() 调用的某个函数中播种PRNG 可能会更好。每次运行程序时,您都希望准确地播种一次。
  • @Raven:不,把它移到你的main()。您也不希望每次洗牌时都播种。
【解决方案2】:

因为您每次在循环中都使用相同的种子(它在不到一秒的时间内运行)播种随机数生成器。在程序开始时调用srand48() ONCE。

【讨论】:

    【解决方案3】:

    PRNG 始终是确定性的...PRNG 的随机性不是通过它的逻辑来实现的,而是通过它使用的种子来实现的。

    因此,使种子尽可能随机以实现随机性。

    【讨论】:

      猜你喜欢
      • 2013-04-23
      • 2019-08-17
      • 1970-01-01
      • 1970-01-01
      • 2014-04-06
      • 2010-10-30
      • 2021-02-07
      • 1970-01-01
      • 2011-04-14
      相关资源
      最近更新 更多