为什么我总是得到的随机数字。兰特相同的序列()? [英] Why do I always get the same sequence of random numbers with rand()?
问题描述
这是第一次我试图用C随机数(我想念C#)。这里是我的code:
This is the first time I'm trying random numbers with C (I miss C#). Here is my code:
int i, j = 0;
for(i = 0; i <= 10; i++) {
j = rand();
printf("j = %d\n", j);
}
本code,每次都遇到我运行code时相同的序列。但是,如果我加入函数srand(/ * someValue中/ *)
在为
循环它生成不同的随机序列。任何人都可以解释为什么?
with this code, I get the same sequence every time I run the code. But it generates different random sequences if I add srand(/*somevalue/*)
before the for
loop. Can anyone explain why?
推荐答案
您已经播种了。随着时间的播种它是一个好主意:
You have to seed it. Seeding it with the time is a good idea:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main ()
{
srand ( time(NULL) );
printf ("Random Number: %d\n", rand() %100);
return 0;
}
您得到相同的顺序,因为RAND()会自动为1的值播种,如果你不调用srand()函数。
You get the same sequence because rand() is automatically seeded with the a value of 1 if you do not call srand().
的由于意见的
兰特()
将返回0和 RAND_MAX之间的一个数
(在标准库中定义)。使用模操作符(%
)给出的余兰特()/ 100
。这将迫使该随机数是0到99范围之内。例如,为了得到0-999范围内的随机数,我们将适用兰特()%1000
。
rand()
will return a number between 0 and RAND_MAX
(defined in the standard library). Using the modulo operator (%
) gives the remainder of the division rand()/100
. This will force the random number to be within the range 0-99. For example, to get a random number in the range of 0-999 we would apply rand()%1000
.
这篇关于为什么我总是得到的随机数字。兰特相同的序列()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!