为什么没有显示最后一个console.log()输出?

时间:2018-02-22 15:30:40

标签: javascript

我正在尝试使用JavaScript制作一个非常简单的“猜数字”游戏。

我希望它的最大限制为5次猜测。如果您猜测,该程序会告诉您有多少次尝试得到答案并在超过5次猜测时停止游戏。

我只有一个问题。如果您的第5次猜测错误,它只会显示消息“您使用了5次猜测,解决方案是10”,我还想显示您的最后一次猜测并使用相应的消息(“go”更高“/”更低“)。

你能帮帮我吗?出于这个问题的目的,我改变了用固定变量而不是随机变量猜测的数字。



var solution = 10;
var n = prompt("Enter a number");
var i = 1;

while ((i < 5) && (n != solution)) {
  console.log(n + " is too " + ((n < solution) ? "small" : "big"));
  n = prompt("Try again");
  i++;
}

if (n == solution) {
  console.log("Good job, the solution was " + n + " you got that in " + i + " tries")
}
else {
  console.log(" You lost, your " + i + " tries have ended")
}
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

只需添加以下行:

@get

在最后一个else语句中,你应该没问题

&#13;
&#13;
console.log( n + " is too " + ((n < solution) ? "small" : "big"));
&#13;
&#13;
&#13;

答案 1 :(得分:0)

试试这个:

&#13;
&#13;
var solution = 10;
var n;
var i = 0; // don't read input here, and set i to 0 not 1


while( ( i < 5 )  &&  ( n != solution)){

    if(i==0){n = prompt ("Enter number");}
    else{n = prompt ("Try again");}
    console.log( n + " is too " + ((n < solution) ? "small" : "big")); // write that AFTER reading input, not BEFORE.
    i++;
}

if ( n == solution ){
    console.log("Good job, the solution was " + n + " you got that in " + i + " tries")
}

else {
   console.log(" You lost, your " + i + " tries have ended")
}
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我编辑了你的最后一个console.log语句。根据我的问题理解,这会产生您想要的结果。

var solution = 10;
var n = prompt("Enter a number");
var i = 1;

while ((i < 5) && (n != solution)) {
  console.log(n + " is too " + ((n < solution) ? "small" : "big"));
  n = prompt("Try again");
  i++;
}

if (n == solution) {
  console.log("Good job, the solution was " + n + " you got that in " + i + " tries")
}
else {
  console.log(n + " is too " +((n < solution) ? "small." : "high.") + " You lost. Your 5 tries have ended." )
}