while循环,是循环结果而不是通过问题

时间:2018-04-13 12:32:41

标签: javascript node.js loops while-loop

我在节点中创建一个数字猜谜游戏,但是我的while循环假设循环问题(请猜测0-maxNum之间的数字,当先前猜到的答案不正确时。)如果是ranNum,我已经做到了是不是数字猜测循环不相等,如果它是真的,我添加了一个休息的声明,但我似乎无法弄清楚,如果有人有任何想法可以帮助!)

let maxNum= readlineSync.question(name +" "+'choose a number between ' + 0 
        +" 
         "+ ' and ' +  number + '\n') 
        //   }
    if (maxNum > number) {
    console.log(`You cannot use a number greater than ` + number)

  let ranNum = Math.floor(Math.random() * maxNum) + 1; 

      while(ranNum !== number) 
     {

         if (number === ranNum) {
           console.log('Correct! The number was ' + ranNum)
        break;
    } else if ( ranNum >  number) {
        console.log('Close! Too high.');
    } else if ( ranNum < number) {
        console.log('Almost! Too low.');
    }
}
     }
    }

1 个答案:

答案 0 :(得分:0)

你不需要做一个while循环,这会让你在答案不正确时陷入循环。

我认为这段代码与你想做的事情是一样的。

<html>
<head>
    <script>
    var MAX = 50;
    var ranNum = Math.floor(Math.random() * MAX) + 1;
    function test(){
    var number = parseInt(document.forms["form"]["in"].value);
        if (number == ranNum) {
            alert('Correct! The number was ' + ranNum)
        } else if ( ranNum >  number) {
            alert('Close! Too high.');
        } else if ( ranNum < number) {
            alert('Almost! Too low.');
        }
    }
    </script>
</head>
<body>
    <form name = "form" onsubmit = "test()">
        <input type = "textarea" name = "in" />
        <input type = "submit" value = "submit"/>
    </form>
</body>

我希望你回答这个问题。