【问题标题】:How to generate different random numbers in one single runtime?如何在一个运行时生成不同的随机数?
【发布时间】:2013-02-10 06:08:16
【问题描述】:

考虑这段代码:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
  int ctr;
  for(ctr=0;ctr<=10;ctr++)
    {
      int iSecret;
      srand ( time(NULL) );
      printf("%d\n",iSecret = rand() % 1000 + 1);
    }
}

它会输出: 256 256 256 256 256 256 256 256 256 256

不幸的是,我希望输出在该循环中打印 10 个不同的随机数。

【问题讨论】:

  • 将那些能帮助你的人称为“天才”可能会被认为是粗鲁的。我建议你编辑你的帖子。
  • 你为什么一直srand呢?

标签: c random srand


【解决方案1】:

将对srand(time(NULL)); 的调用移动到for 循环之前。

问题在于 time() 每秒只更改一次,但您生成 10 个数字,除非您的 CPU 非常慢,否则生成不会花费一秒钟这 10 个随机数。

因此,您每次都使用相同的值重新播种生成器,使其返回相同的数字。

【讨论】:

  • @paxdiablo 感谢您的编辑。 (这让我觉得我应该提高我的英语技能...... :( )
  • Fogadok, hogy az angol is jobb, mint a magyar: 我敢打赌你的英语比我的匈牙利语好:-)
  • @paxdiablo 就目前而言,这句话的意思是“我打赌英语也比匈牙利语好”;-) “Fogadok, hogy te jobban beszélsz angolul, mint én magyraul。”
  • 因此证明我对我们的相对语言技能是正确的,或者谷歌翻译主要是 marhaság :-)
  • @paxdiablo 谷歌翻译实际上非常擅长翻译语法足够一致的语言。匈牙利语不是其中之一 ;-)
【解决方案2】:

srand ( time(NULL) ); 放在循环之前。您的循环可能会在一秒钟内运行,因此您正在使用相同的值重新初始化种子。

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
  int ctr;
  srand ( time(NULL) );
  for(ctr=0;ctr<=10;ctr++)
    {
      int iSecret;
      printf("%d\n",iSecret = rand() % 1000 + 1);
    }
}

【讨论】:

    【解决方案3】:

    将 srand(time(0)) 保留在 for 循环之外。 它不应该在那个循环内。

    #include <stdio.h>
    #include <stdlib.h>
    #include <time.h>
    int main ()
    {
      int ctr;
      srand ( time(NULL) );
      for(ctr=0;ctr<=10;ctr++)
        {
          int iSecret;
          printf("%d\n",iSecret = rand() % 1000 + 1);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多