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;
答案 0 :(得分:1)
你没有递增randomNum因此它总会保持无限循环。
答案 1 :(得分:1)
您在代码的开头初始化randonNum
和guesses
,但之后您再也不会更改其值。因此,一旦进入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
}
您可以通过在循环中放置一个条件来解决问题,该条件将使用break
或return
突破循环,或者您可以修改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");