0

I'm using srand() with a fixed seed and I need to run tests with a set of different seeds like 100, 200, 300, ..., 1000 all in one execution. Is this possible? The thing is srand() is defined at the beginning of main, so I don't know how to control the seed with a variable.

4

3 回答 3

3

您可以使用 srand(time(NULL)),并包含 time.h 标头。它使用当前系统时间初始化 srand()。希望能帮助到你。!!

于 2012-09-04T04:10:11.597 回答
0

如果单元测试测试使用 rand() 的代码,那么您应该调用srand(<const>)作为测试设置的一部分。

这样,测试的行为方式与作为套件的一部分独立运行的天气相同。

于 2012-09-04T04:29:52.657 回答
0

对于在调用 srand 时使用的每个不同的种子值,可以预期伪随机数生成器在随后调用 rand 时生成不同的连续结果。具有相同种子的两个不同初始化指示伪随机生成器在两种情况下为随后对 rand 的调用生成相同的连续结果。

这可能说明:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  printf ("First number: %d\n", rand() % 100);
  srand ( time(NULL) );

  printf ("Random number: %d\n", rand() % 100);
  srand ( 1 );

  printf ("Again the first number: %d\n", rand() %100);
  srand ( time(NULL) );

  printf ("Random number: %d\n", rand() % 100);

  printf ("Random number: %d\n", rand() % 100);

  printf ("Random number: %d\n", rand() % 100);

  printf ("Random number: %d\n", rand() % 100);

  return 0;
}

输出:

First number: 41
Random number: 76
Again the first number: 41
Random number: 76
Random number: 14
Random number: 74
Random number: 41
Press any key to continue
于 2012-09-04T05:10:39.973 回答