0

次のコードを検討してください。

#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 個の異なる乱数を出力する必要があります。

4

3 に答える 3

6

への呼び出しをループsrand(time(NULL));の前に移動します。for

問題はtime()、1 秒に 1 回しか変化しないということですが、10 個の数値を生成しているため、極端に遅い CPU を使用していない限り、これらの 10 個の乱数を生成するのに 1 秒もかかりません。

したがって、毎回同じ値でジェネレーターを再シードしているため、同じ数値が返されます。

于 2013-02-10T06:10:45.863 に答える
1

srand ( time(NULL) );ループの前に置きます。ループはおそらく 1 秒以内に実行されるため、同じ値でシードを再初期化しています。

#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);
    }
}
于 2013-02-10T06:12:05.780 に答える