无法检测为什么我的循环是无限的

时间:2016-08-27 21:52:29

标签: javascript while-loop



var randomNum = Math.round(Math.random() * 100);
guesses = prompt("guess a number between 1 and 100");
var scores = 0;
while (randomNum < 100) {
    if (guesses < randomNum) {
        console.log(" too low.. continue")
    } else if (guesses > randomNum) {
        console.log("too high ... continue ");
        score++;
    } else if (guesses === randomNum) {
        console.log("great ... that is correct!!")
    } else {
        console.log("game over ... your guess was right  " + scores + " times");
    }
}
&#13;
&#13;
&#13; 我一直在与while循环概念挣扎一段时间,为了面对我的恐惧,我决定练习上面的一些小练习。

4 个答案:

答案 0 :(得分:1)

你没有递增randomNum因此它总会保持无限循环。

答案 1 :(得分:1)

您在代码的开头初始化randonNumguesses,但之后您再也不会更改其值。因此,一旦进入while循环并且条件开始为假,则while循环内部没有任何内容可以更改比较条件的结果。因此,条件总是错误的,最终会出现无限循环。你的循环结构归结为:

while (randomNum < 100) {
    // randomNum never changes
    // there is no code to ever break or return out of the loop
    // so loop is infinite and goes on forever
}

您可以通过在循环中放置一个条件来解决问题,该条件将使用breakreturn突破循环,或者您可以修改randomNum中的guesses === randomNum的值循环使得循环最终会自行终止。

此外,guesses永远不会成为现实,因为randomNum是一个字符串而prompt()是一个数字,因此您也必须修复该比较。

并不是100%清楚你想要实现的目标,但是如果你试图让用户反复猜测数字直到他们做对了,那么你需要在while循环中放一个var randomNum = Math.round(Math.random() * 100); var guess; var score = 0; while ((guess = prompt("guess a number between 1 and 100")) !== null) { // convert typed string into a number guess = +guess; if (guess < randomNum) { console.log(" too low.. continue") } else if (guess > randomNum) { console.log("too high ... continue "); score++; } else if (guess === randomNum) { console.log("great ... that is correct!!") console.log("score was: " + score); // when we match, stop the while loop break; } } 并且当他们说得对或要求取消时,他们会在while循环中突破:

include()

答案 2 :(得分:0)

您的分配randomNum下面的代码行只有一次,因此它不会改变

var randomNum = Math.round(Math.random() * 100);

因此,当您尝试创建while循环时,randomNum值保持不变

尝试更改while循环中的randomNum

答案 3 :(得分:0)

我认为这是你想要实现的目标。重试x次

var randomNum = Math.round(Math.random() * 100);
var guesses;
var scores = 0;
var tries = 0
while (tries++ < 3) { // Loop if less than 3 tries, and increment
  guesses = prompt("guess a number between 1 and 100");

  if (guesses < randomNum) {
    console.log(" too low.. continue")
  } else if (guesses > randomNum) {
    console.log("too high ... continue ");
  } else {
    // It's not to low, not to high. It must be correct
    score++;
    console.log("great ... that is correct!!");
    randomNum = Math.round(Math.random() * 100);
  }
}

console.log("game over ... your guess was right  " + scores + " times");