为什么这种情况不能正常工作?

时间:2014-06-23 09:21:43

标签: javascript

我必须做一个数字猜谜游戏,你有三次尝试猜测1到5之间的数字。每次错误的猜测后,它会显示你剩下的尝试次数。当你猜对了,你会收到祝贺信。当你用完猜测时,你会收到一条消息。但是,当你跑出猜测时,我无法得到消息。为什么不运行?

<script type="text/javascript">
    var tries=3;
    alert("Guess the number I'm thinking of between 1 and 5. You've got 3  tries.");
    var attempt =  prompt(tries+" tries remaining. Enter your guess.");
    var randomnumber = Math.random() * 5; 
    randomnumber = Math.ceil(randomnumber);
    while (tries>=2){
        if(attempt!=randomnumber){
            tries--;
            prompt("Wrong! You have " + tries + " left ");
        }
        else if(tries<1){
            alert("You have no tries left");
        }
        else {
            alert("Congratulations! You guessed the correct number");
            return;
        }
    }
</script>

3 个答案:

答案 0 :(得分:4)

当你有2次或2次尝试时,你才进入循环。否则你的if语句不会被执行。你可能不得不分开你的if。

<script type="text/javascript">
    var tries=3;
    alert("Guess the number I'm thinking of between 1 and 5. You've got 3  tries.");
    var attempt =  prompt(tries+" tries remaining. Enter your guess.");
    var randomnumber = Math.random() * 5; 
    randomnumber = Math.ceil(randomnumber);
    while (tries-1 > 0){
        if(attempt!=randomnumber){
            tries--;
            prompt("Wrong! You have " + tries + " left ");
        }
        else {
            alert("Congratulations! You guessed the correct number");
            return;
        }
    }
    alert("You have no tries left");
</script>

答案 1 :(得分:0)

问题在于您的支票tries>=2。我已经修改了你的代码,它按照要求工作

var tries = 3;
alert("Guess the number I'm thinking of between 1 and 5. You've got 3  tries.");
var attempt = prompt(tries + " tries remaining. Enter your guess.");
var randomnumber = Math.floor(Math.random() * 5);
while (tries-1 > 0) {
    if (attempt != randomnumber) {
        tries--;
        prompt("Wrong! You have " + tries + " left ");
    } else {
        alert("Congratulations! You guessed the correct number");
        return;
    }
}
alert("You have no tries left");
return;
  • 你可以在一行获得一个随机数

  • 将逻辑拆分为两层 - 虽然您猜测是否猜对了,否则返回“没有猜错”消息

jsFiddle

答案 2 :(得分:0)

您必须影响attempt变量的每次尝试:

<script type="text/javascript">
    var tries=3;
    alert("Guess the number I'm thinking of between 1 and 5. You've got 3  tries.");
    var randomnumber = Math.random() * 5; 
    randomnumber = Math.ceil(randomnumber);
    var attempt;
    var success = false;
    while (tries>0 && !success){
        attempt = prompt(tries+" tries remaining. Enter your guess.");
        tries--;
        if(attempt!=randomnumber){
            alert("Wrong! You have " + tries + " left ");
        } else {
            success = true;
        }
    }
    if(success){
        alert("Congratulations! You guessed the correct number");
    } else {
        alert("You have no tries left");
    }
</script>

Working fiddle