問題描述
我有一個(gè)運(yùn)行 15 次的 for
循環(huán),每次迭代都使用 dh.setDoors()
.
I have a for
loop that runs 15 times, with dh.setDoors()
in every iteration.
setDoors
所做的是調(diào)用 srand(time(0))
,然后每當(dāng)需要隨機(jī)數(shù)時(shí)它都會(huì)使用,例如 carSetter =rand()%3+1
.或者,它可以使用 decider = rand()%2+1
.
What setDoors
does is call srand(time(0))
, then whenever a random number is needed it'll use, for example, carSetter = rand()%3+1
. Alternatively, it may use decider = rand()%2+1
.
現(xiàn)在,通常decider
和carSetter
以不同的方式使用,但我懷疑有問題并打印出carSetter
和decider
在每次迭代中.這是結(jié)果:
Now, normally decider
and carSetter
are used in a different ways, but I suspected a problem and made it print out carSetter
and decider
at every iteration. Here's what came out:
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
Door 1 has car
Decider is 2
etc...
當(dāng)我多次運(yùn)行它時(shí),值1"和2"會(huì)發(fā)生變化,但在 15 次中仍然相同.
The values '1' and '2' change when I run it multiple times, but are still the same throughout the 15 times.
既然循環(huán)運(yùn)行了 15 次不同的時(shí)間,難道 carSetter
和 decider
不應(yīng)該每次迭代都打印出不同的隨機(jī)數(shù)嗎?
Since the loop is running 15 different times, shouldn't carSetter
and decider
print out a different random number every iteration?
當(dāng)我沒有 srand(time(0))
時(shí),它按預(yù)期工作,但是沒有種子集,所以每次都是相同的隨機(jī)"數(shù)字序列,所以它是可能是種子有問題?
When I don't have srand(time(0))
, it works as expected, but there's no seed set, so it's the same sequence of "random" numbers each time, so it's probably a problem with the seed?
推薦答案
當(dāng)你調(diào)用 srand(x)
時(shí),那么 x
的值決定了偽序列在對(duì) rand()
的后續(xù)調(diào)用中返回的隨機(jī)數(shù),完全取決于 x
的值.
When you call srand(x)
, then the value of x
determines the sequence of pseudo-random numbers returned in following calls to rand()
, depending entirely on the value of x
.
當(dāng)您處于循環(huán)中并在頂部調(diào)用 srand()
時(shí):
When you're in a loop and call srand()
at the top:
while (...) {
srand(time(0));
x = rand();
y = rand();
}
然后根據(jù)time(0)
返回的值生成相同隨機(jī)數(shù)序列.由于計(jì)算機(jī)速度很快,而且您的循環(huán)可能會(huì)在不到一秒的時(shí)間內(nèi)運(yùn)行,time(0)
每次通過循環(huán)都會(huì)返回 相同 值.所以 x
和 y
每次迭代都是一樣的.
then the same random number sequence is generated depending on the value that time(0)
returns. Since computers are fast and your loop probably runs in less than a second, time(0)
returns the same value each time through the loop. So x
and y
will be the same each iteration.
相反,您通常只需要在程序開始時(shí)調(diào)用 srand()
一次:
Instead, you only usually need to call srand()
once at the start of your program:
srand(time(0));
while (...) {
x = rand();
y = rand();
}
在上面的例子中,x
和 y
每次循環(huán)都會(huì)有不同的值.
In the above case, x
and y
will have different values each time through the loop.
這篇關(guān)于每次循環(huán)迭代相同的隨機(jī)數(shù)的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!