Same random numbers every loop iteration(每次循环迭代相同的随机数)
问题描述
我有一个运行 15 次的 for
循环,每次迭代都使用 dh.setDoors()
.
I have a for
loop that runs 15 times, with dh.setDoors()
in every iteration.
setDoors
所做的是调用 srand(time(0))
,然后每当需要随机数时它都会使用,例如 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
.
现在,通常decider
和carSetter
以不同的方式使用,但我怀疑有问题并打印出carSetter
和decider
在每次迭代中.这是结果:
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...
当我多次运行它时,值1"和2"会发生变化,但在 15 次中仍然相同.
The values '1' and '2' change when I run it multiple times, but are still the same throughout the 15 times.
既然循环运行了 15 次不同的时间,难道 carSetter
和 decider
不应该每次迭代都打印出不同的随机数吗?
Since the loop is running 15 different times, shouldn't carSetter
and decider
print out a different random number every iteration?
当我没有 srand(time(0))
时,它按预期工作,但是没有种子集,所以每次都是相同的随机"数字序列,所以它是可能是种子有问题?
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?
推荐答案
当你调用 srand(x)
时,那么 x
的值决定了伪序列在对 rand()
的后续调用中返回的随机数,完全取决于 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
.
当您处于循环中并在顶部调用 srand()
时:
When you're in a loop and call srand()
at the top:
while (...) {
srand(time(0));
x = rand();
y = rand();
}
然后根据time(0)
返回的值生成相同随机数序列.由于计算机速度很快,而且您的循环可能会在不到一秒的时间内运行,time(0)
每次通过循环都会返回 相同 值.所以 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.
相反,您通常只需要在程序开始时调用 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
每次循环都会有不同的值.
In the above case, x
and y
will have different values each time through the loop.
这篇关于每次循环迭代相同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:每次循环迭代相同的随机数
基础教程推荐
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01