为什么在循环外生成随机数,使其始终相同? [英] Why does generating a random number outside of a loop, causes it to be always the same?

查看:25
本文介绍了为什么在循环外生成随机数,使其始终相同?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在 while 循环中创建一个随机数作为局部变量时,一切正常,但是当我生成一个随机数作为全局变量时,我就会陷入无限循环.
我不明白这应该如何以及为什么会有所作为.目标是用While循环输出所有小于0.7的随机数.

When I create a random number inside a while loop as a local variable everything works, but when I generate a random number as a global variable then I get stuck in an infinite loop.
I don't understand how and why this should make any difference. Goal is to output all the random numbers that are less than 0.7 with a While Loop.

这是创建无限循环的代码:

Here is the code that creates an infinite loop:

let rnd = Math.random();
let continue = true;

while (continue) {
  console.log(rnd);
  if (rnd > 0.7) {
    continue = false;
    alert(rnd + ' is bigger than 0.7!');
  }
}

这是有效的代码(唯一改变的是随机数是在while循环中生成的).

Here is the code that works (only thing that is changed is that the random number is generated within the while loop).

let continue = true;

while (continue) {
  let rnd = Math.random();
  console.log(rnd);
  if (rnd > 0.7) {
    continue = false;
    alert(rnd + ' is bigger than 0.7!');
  }
}

我对用另一种循环创建它不感兴趣,我只是想更好地理解 While 循环.

I'm not interested in creating this with another kind of loop, I'm just trying to understand the While Loop better.

推荐答案

这是因为当你将 Math.random() 声明为一个变量时,它会创建一个带有随机值的绑定,它不会改变.示例:0.8.

It is because when you declare Math.random() as a variable it creates a binding with a random value which doesn't change. Example: 0.8.

如果它小于或等于 0.7,那么它将导致无限循环,因为该值不会随着每次迭代而改变.

And if it is less than or equal to 0.7 then it would result in an infinite loop because the value doesn't change with each iteration.

在第二个示例中,它运行良好,因为它是在本地声明的,并且每次迭代时它的值都会发生变化.

In the second example it works fine because it is declared locally and it's value changes with each iteration.

希望你理解.

这篇关于为什么在循环外生成随机数,使其始终相同?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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