猜猜比赛的困境

时间:2014-09-14 17:41:19

标签: javascript random numbers

您好我是javascript的新手并且一直试图制作一个随机数字猜谜游戏。我想我几乎得到了它,除了有一件事我无法弄清楚。每次我运行它我必须输入我的号码两次,它也只返回低,无论我输入什么号码。

var randomNumber = Math.floor((Math.random() * 100) + 1);

print("I have thought of a random number in the range of 1 to 100. Guess!");
{ 
    while (randomNumber != readline())
        if (readline() < randomNumber) 
        {
            print("Lower");
        } 
        else if (readline() > randomNumber) 
        {
            print("Higher");
        } 
        else if (readline() == randomNumber) 
        {
            print("Good Job");
        }
}

1 个答案:

答案 0 :(得分:0)

你的问题是你在while循环的每次迭代中多次调用readline。在这里,我将readline的值存储到变量中并使用它来测试:

var randomNumber = Math.floor((Math.random() * 100) + 1);

print("I have thought of a random number in the range of 1 to 100. Guess!");

var hasGuessedCorrectly = false;

while (!hasGuessedCorrectly) 
{
    var guess = readline();
    if (guess < randomNumber) 
    {
        print("Lower");
    } 
    else if (guess > randomNumber) 
    {
        print("Higher");
    } 
    else if (guess == randomNumber) 
    {
        print("Good Job");
        hasGuessedCorrectly = true;
    }
}