每个循环迭代相同的随机数 [英] Same random numbers every loop iteration

查看:91
本文介绍了每个循环迭代相同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 for 循环运行15次,在每次迭代中 dh.setDoors() / p>

setDoors 是调用 srand(time(0)),那么每当需要一个随机数时,它将使用例如 carSetter = rand()%3 + 1 。或者,它可以使用 decider = rand()%2 + 1



现在,通常 decider carSetter 以不同的方式使用,但我怀疑是一个问题,并打印出 carSetter 决定器。这是出来的:

 门1有车
决定是2
门1有车
决定者是2
门1有汽车
决定者是2
门1有汽车
决定者是2
门1有汽车
决定者是2
etc ...

当我运行时,值'1'和'2'



由于循环运行了15次不同的时间,因此不应 carSetter code>和决定器每次迭代打印一个不同的随机数?



srand(time(0)),它按预期工作,但没有种子集,所以每次都是相同的随机数字序列,所以这可能是一个问题 c> 当你调用 srand(x)时,那么 x 的值确定在随后调用 rand()时返回的伪随机数的序列,完全依赖于 x 的值。



srand()在顶部:

  {
srand(time(0));
x = rand();
y = rand();
}

,则会生成相同随机数序列对 time(0)返回的值。由于计算机速度快,你的循环可能在不到一秒钟内运行, time(0)每次通过循环返回相同的值。因此 x y 将在每次迭代时都是相同的。



<相反,您通常只需在程序开始时调用 srand() 一次

  srand(time(0)); 

while(...){
x = rand();
y = rand();
}

在上述情况下, x y 在每次循环时都会有不同的值。


I have a for loop that runs 15 times, with dh.setDoors() in every iteration.

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.

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...

The values '1' and '2' change when I run it multiple times, but are still the same throughout the 15 times.

Since the loop is running 15 different times, shouldn't carSetter and decider print out a different random number every iteration?

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?

解决方案

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.

When you're in a loop and call srand() at the top:

while (...) {
    srand(time(0));
    x = rand();
    y = rand();
}

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.

Instead, you only usually need to call srand() once at the start of your program:

srand(time(0));

while (...) {
    x = rand();
    y = rand();
}

In the above case, x and y will have different values each time through the loop.

这篇关于每个循环迭代相同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆