简单的JavaScript功能,只要求用户5次正确答案?

时间:2018-02-17 20:20:36

标签: javascript loops input prompt

我正在尝试使用JavaScript开发一个非常简单的函数,提示用户输入一个数字,然后给他们5次机会猜测给定数字的平方。

因此,例如,如果用户在第一个提示符中输入6,则他们应该在第二个提示符中输入36,但是如果他们未能使其正确,则会收到错误消息,表明猜测的数字是错误的。并且它们仅限于5次机会,因此在此之后,程序不会再次提示用户。

我尝试做这样的事情来保持简单:

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries");
if (input2 == input*input) {
    alert("Good!");
} else {
    prompt("Wrong, enter again!");
}

我是在正确的道路上吗?我的意思是它没有做我想做的事情,但我真的陷入了困境。不知道如何循环5次,或下一步做什么。

4 个答案:

答案 0 :(得分:1)

试试这个

function guessSquare() {
    var input = parseInt(window.prompt("Enter a number", "Enter here"));
    var c = 5;
    var message = "Guess its square now in 5 tries";
    (function receiveAnswer() {
        var input2 = parseInt(window.prompt(message));
        if (input2 == input * input) {
            alert("Good!");
        } else {
            c--;
            if (c === 0) {
                alert("Ran out of attempts!");
            } else {
                message = "Wrong, enter again! " + c + " attempts left!";
                receiveAnswer();
            }
        }
    })();
}

答案 1 :(得分:0)

你错过了一个结束括号:

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries")); //<--- here

if (input2 == input*input) {
  alert("Good!");
} else {
  prompt("Wrong, enter again!");
}

...你需要一个循环。最简单的理解是for

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));

for (var i = 0; i < 5; i++) {
  if (input2 == input*input) {
    alert("Good!");
    i = 5;
  } else {
    input2 = prompt("Wrong, enter again!")
  }
}
    

答案 2 :(得分:0)

使用do-while

var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));

var tries = 1;
do {
  if (input2 == input * input) {
    alert("Good!");
    break;
  } else {
    prompt("Wrong, enter again!");
  }
} while (++tries < 5);

答案 3 :(得分:0)

&#13;
&#13;
var input = parseInt(window.prompt("Enter a number", "Enter here"));
var input2 = parseInt(window.prompt("Guess its square now in 5 tries"));

var tries = 0;
do {
  if (input2 == input * input) {
    alert("Good!");
    break;
  } else {
    input2 = parseInt(window.prompt("Wrong, enter again!"));
  }
} while (++tries < 5);
&#13;
&#13;
&#13;