C语言 如何在 time.h 中使用函数 srand()?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16569239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use function srand() with time.h?
提问by ?ēēpak
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.
我的程序包含每次执行时都应该生成一个随机正整数的代码。它生成随机数,但只生成一次。之后,当我执行相同的代码时,它给了我相同的值,这使我的代码变得无用。
I started with the randfunction, and then I used the srand()function with the time.hheader file, but still it is not working properly.
我从rand函数开始,然后我将srand()函数与time.h头文件一起使用,但它仍然无法正常工作。
#define size 10
for(i=0;i<size;i++)
Arr[i] = rand()%size;
First call (random):
第一次调用(随机):
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
Later I visited Stack Overflow questions and I read about the srand() function, and I used it as:
后来我访问了 Stack Overflow 问题并阅读了 srand() 函数,并将其用作:
#include<time.h>
for(i=0;i<size;i++)
Arr[i] = srand(time(NULL));
First call:
第一次调用:
-10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327 -10327
Second call:
第二次调用:
-10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326 -10326
It is giving me different (but not random values). I've defined Arr[i] as unsigned int, and still I am getting negative values.
它给了我不同的(但不是随机值)。我已将Arr[i]定义为 unsigned int,但仍然得到负值。
回答by Paul R
You need to call srand()once, to randomize the seed, and then call rand()in your loop:
您需要调用srand()一次,随机化种子,然后rand()在循环中调用:
#include <stdlib.h>
#include <time.h>
#define size 10
srand(time(NULL)); // randomize seed
for(i=0;i<size;i++)
Arr[i] = rand()%size;
回答by Ze..
Try to call randomize() before rand() to initialize random generator.
尝试在 rand() 之前调用 randomize() 来初始化随机生成器。
(look at: srand() — why call it only once?)
回答by Grady Player
If you chose to srand, it is a good idea to then call rand()at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.
如果您选择srand,那么rand()在使用它之前至少调用一次是个好主意,因为它是一种可怕的原始伪随机生成器。请参阅堆栈溢出问题为什么 rand() % 7 总是返回 0?.
srand(time(NULL));
rand();
//Now use rand()
If available, either randomor arc4randwould be better.
如果可用,无论是random或arc4rand将是更好的。
回答by R.M.VIVEK Arni
#include"stdio.h"
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int i;
srand(time(&t));
for(i=1;i<=10;i++)
printf("%c\t",rand()%10);
getch();
}
回答by R.M.VIVEK Arni
#include"stdio.h"//rmv coding for randam number access
#include"conio.h"
#include"time.h"
void main()
{
time_t t;
int rmvivek;
srand(time(&t));
rmvivek=1;
while(rmvivek<=5)
{
printf("%c\t",rand()%10);
rmvivek++;
}
getch();
}

