为什么我的C随机数发生器只返回" 42';? [英] Why does my C random number generator only return "42"?

查看:324
本文介绍了为什么我的C随机数发生器只返回" 42';?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作为真棒一个偶然的功能,因为这是,它使一个糟糕的方​​式来洗牌的卡的数组。那我得到了相同数量的事实告诉我,我已经有在挑选单独的种子每次一些问题。我使用 srand48 时间(NULL)调用不正确?有一些背后的逻辑缺陷,我失踪?在那里只是没有足够的时间其间迭代的时间值()是不同的?

在code正在运行在Linux上。

 无效洗牌(){
  INT i_rnd; / *整数随机数,范围0..100 * /
  诠释i_rnd2;
  卡tempCard; / *临时卡facillitate交换* /
  INT I = 0; / *因为我们是没有使用C99标准*不能使用FOR循环'/
  而(ⅰ&下; 1000)
  {      srand48((无符号)时间(NULL)); / *种子的随机数发生器* /
      i_rnd =(int)的(drand48()* 100);
      i_rnd = i_rnd%52; //返回一个随机数0-51
      i_rnd2 =(int)的(drand48()* 100);
      i_rnd2 = i_rnd2%52; //返回一个随机数0-51
      / *我们有两个随机数,现在交换与两个对象
      /挑数组索引* /
      tempCard = cardDeck [i_rnd]
      cardDeck [i_rnd] = cardDeck [i_rnd2]
      cardDeck [i_rnd2] = tempCard;
      //交换完成。增量计数器,以便我们能够最终走出同时
      我++;  }返回;}


解决方案

您需要播种伪随机数发生器的一次的,不是每次你使用它。

许多(大多数?)伪随机数生成器(PRNG)是确定性给予一定的种子值。如果时间()返回每个循环执行的时间相同的值,你播种PRNG你使用它之前每次都相同的值,所以当你查询它随机数字它返回的值相同。

As awesome an accidental feature as this is, it makes for a lousy way to "shuffle" an array of "cards". The fact that I'm getting the same number tells me I've having some problem in picking separate seeds each time. Am I using srand48 or the time(NULL) call improperly? Is there some underlying logic flaw I'm missing? Is there just not enough time inbetween iterations for the value of time() to be different?

The code is being run on 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;

}

解决方案

You need to seed the pseudorandom number generator once, not every time you use it.

Many (most?) pseudorandom number generators (PRNG) are deterministic given a certain seed value. If time() returns the same value each time your loop executes, you seed the PRNG with the same value just before you use it each time, so when you query it for random numbers it returns the same values.

这篇关于为什么我的C随机数发生器只返回&QUOT; 42';?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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