如何在 time.h 中使用函数 srand()? [英] How to use function srand() with time.h?
问题描述
我的程序包含每次执行时都应该生成一个随机正整数的代码.它生成随机数,但只生成一次.之后,当我执行相同的代码时,它给了我相同的值,这使我的代码变得毫无用处.
My program contains code that should generate a random positive integer number every time I execute it. It generates random numbers but only once. After that, when I execute same code, it gives me same values, and it is making my code useless.
我从 rand 函数开始,然后将 srand() 函数与 time.h 头文件一起使用,但仍然它工作不正常.
I started with the rand function, and then I used the srand() function with the time.h header file, but still it is not working properly.
#define size 10
for(i=0;i<size;i++)
Arr[i] = rand()%size;
第一次调用(随机):
6 0 2 0 6 7 5 5 8 6
第二次调用(随机但与之前相同):
Second call (random but same as previous):
6 0 2 0 6 7 5 5 8 6
<小时>
后来我访问了 Stack Overflow 问题并阅读了 srand() 函数,我将其用作:
Later I visited Stack Overflow questions and I read about the srand() function, and I used it as:
#include<time.h>
for(i=0;i<size;i++)
Arr[i] = srand(time(NULL));
第一次调用:
-10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327
第二次调用:
-10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326
它给了我不同的(但不是随机值).我已将 Arr[i] 定义为 unsigned int,但仍然得到负值.
It is giving me different (but not random values). I've defined Arr[i] as unsigned int, and still I am getting negative values.
推荐答案
需要调用srand()
一次,随机化种子,然后调用rand()
在你的循环中:
You need to call srand()
once, to randomize the seed, and then call rand()
in your loop:
#include <stdlib.h>
#include <time.h>
#define size 10
srand(time(NULL)); // randomize seed
for(i=0;i<size;i++)
Arr[i] = rand()%size;
这篇关于如何在 time.h 中使用函数 srand()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!