为什么我总是用 rand() 得到相同的随机数序列? [英] Why do I always get the same sequence of random numbers with rand()?
问题描述
这是我第一次用 C 尝试随机数(我想念 C#).这是我的代码:
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
", j);
}
使用此代码,每次运行代码时我都会得到相同的序列.但是如果我在 for
循环之前添加 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
", rand() %100);
return 0;
}
您会得到相同的序列,因为如果您不调用 srand()
,rand()
会自动以 a 值作为种子.
You get the same sequence because rand()
is automatically seeded with the a value of 1 if you do not call srand()
.
由于评论
rand()
将返回一个介于 0 和 RAND_MAX
(在标准库中定义)之间的数字.使用 modulo 运算符 (%
) 给出除法的余数 <代码>rand()/100.这将强制随机数在 0-99 范围内.例如,要获得 0-999 范围内的随机数,我们将应用 rand() % 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
.
这篇关于为什么我总是用 rand() 得到相同的随机数序列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!