var coinFlip = Math.round(Math.random());
console.log(coinFlip);
上面的代码在聊天中输入了0或1。 我刚刚了解了while循环...如果为true,则代码运行。
var yes=1;
while (yes<2) {
console.log("Yes");
}
上面的代码将无限运行(在聊天中输入“是”),因为“是”始终小于2。如果可以将“是”设为2,则它将结束。所以...
var coinFlip = Math.round(Math.random());
while (coinFlip < 1) {
console.log(coinFlip);
}
当我尝试将两者结合时,它不起作用。我正在使用repl.it,它会一直持续下去,直到我停止它为止。意思是(我相信)这是一个无限循环。但是我不知道如何。它应该在聊天中记录0,直到达到1,然后停止。
那我在做什么错?
即使我在while循环中声明了coinFlip,它仍然不起作用。我现在更进一步地自学,我可以看到您可以使用for循环运行coinFlip脚本(例如,运行直到运行5次),但我仍然非常想了解为什么您无法运行(使用一段时间),直到达到1。
What you're doing is you're setting a variable
coinFlip
to have a value of either 1 or 0, then running a while loop that keeps checking the same value and printing to the console. So 1 or 2 things will happen:coinFlip
will be 0 and your loop will run forever (because the value ofcoinFlip
never changes; orcoinFlip
will be 1 and theconsole.log
will not even execute because the while condition will be evaluated tofalse
.您需要在循环内移动随机数生成: