当我运行程序时,它将永远不会显示警报(第一个if
语句),即使我猜错了正确的数字。我也可以使用一些关于如何循环程序5次的帮助,我尝试了for
循环但收效甚微。
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 10;
var theNumber = Math.round(timesNumber);
var userInput = prompt("Take a Guess (0-10)");
if(userInput === theNumber) {
alert("You Guessed it! " + userInput + " is correct");
} else if(userInput === theNumber.toString()) {
console.log("Higher");
} else {
console.log("Lower");
}
console.log(theNumber);
答案 0 :(得分:1)
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 10;
var theNumber = Math.round(timesNumber);
while (userInput != theNumber) {
var userInput = prompt("Take a Guess (0-10)");
if(userInput == theNumber) {
alert("You Guessed it! " + userInput + " is correct");
}
else if(userInput < theNumber) {
alert("Higher");
}
else {
alert("Lower");
}
}
答案 1 :(得分:0)
正如@Bergi已经提到的,userImput是一个字符串,而theNumber是一个整数。您可以做的是使用parseInt函数将userImput转换为整数,如下所示:var userImput = parseInt(prompt("Take a Guess (0-10)")) ;
答案 2 :(得分:0)
我有这个问题很长一段时间了。 prompt
函数返回一个字符串。您需要使用parseInt()
将该字符串转换为数字,以便进行数学运算或与之进行比较。
以下是更正后的代码:
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 10;
var theNumber = Math.round(timesNumber);
var userImput = parseInt(prompt("Take a Guess (0-10)"));
if(userImput === theNumber) {
alert("You Guessed it! " + userImput + " is correct");
}
else if(userImput === theNumber) {
console.log("Higher");
}
else {
console.log("Lower");
}
console.log(theNumber);
答案 3 :(得分:0)
在这样的函数中声明它:
function guessingGame() {
var rdmNumber = Math.random();
var timesNumber = rdmNumber * 10;
var theNumber = Math.round(timesNumber);
var userInput = prompt("Take a Guess (0-10)");
if(userInput === theNumber) {
alert("You Guessed it! " + userInput + " is correct");
} else if(userInput === theNumber.toString()) {
console.log("Higher");
} else {
console.log("Lower");
}
console.log(theNumber);
}
并在你的程序中调用它:
var i=0;
while (i < 5) {
guessingGame();
i++;
}