您必须为随机数生成器生成种子。 see here for an example。
未seeded.c
#include <stdio.h>
#include <stdlib.h>
int main()
{
printf ("Random not seeded: %d\n", rand()%10);
return 0;
}
未接种的输出
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
Random not seeded: 3
seeded.c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
printf ("Random seeded: %d\n", rand()%10);
return 0;
}
接种的输出
Random fast seeded: 7
Random fast seeded: 7
Random fast seeded: 7
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 5
Random fast seeded: 5
Random fast seeded: 5
Random fast seeded: 5
fast-seeded.c
如果您希望能够每秒多次调用您的实用程序,您将必须为您的种子使用不同的来源,否则您仍然会得到一些重复的随机数。
这是一个使用纳秒而不是time()
的示例,它只返回秒。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
/* using nano-seconds instead of seconds */
srand((time_t)ts.tv_nsec);
printf ("Random fast seeded: %d\n", rand()%10);
return 0;
}
快种子输出
你可以在这里看到这些数字不进行分组不亚于前面的例子。
Random fast seeded: 9
Random fast seeded: 6
Random fast seeded: 5
Random fast seeded: 6
Random fast seeded: 1
Random fast seeded: 1
Random fast seeded: 9
Random fast seeded: 4
Random fast seeded: 3
Random fast seeded: 2
均匀分布的随机数
如果你有兴趣在均匀分布的随机数,你应该看到下面user3003631的答案。如果你实际上使用C++,那么我会推荐做随机数。 More information here too on this.
提示:在兰特和播种读了随机数发生器。 – tletnes
看起来没有电话[srand](http://www.cplusplus.com/reference/cstdlib/srand/)? – crashmstr
需要调用srand()才能看到函数。查看http://stackoverflow.com/questions/4926622/how-to-generate-different-random-number-in-a-loop-in-c – OldProgrammer