var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = true;
while (userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!');
userIsGuessing++;
if (guess < x && (x - guess) < 15) hint += ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint += ' Way too small!';
else if (guess > x && (x - guess) < 15) hint += ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint += ' Way too big!';
else(guess === x); {
document.writeln("You win! It took you" + userIsGuessing + " times to
guess the number.
");
}
}
我正在尝试使用此代码来要求用户猜测1到100之间的数字。每次用户猜测时,他们都会得到四个提示之一。然后在最后,当他们猜对了,他们会被告知他们花了多少猜测。我真的被困了,请帮帮忙。
答案 0 :(得分:2)
如何开始..
userIsGuessing
是一个布尔值,你应该永远不要使用++ 。检查评论
var x = Math.floor(Math.random() * 100) + 1;
var hint = 'Guess my number, 1-100!';
var userIsGuessing = false; // Boolean, begin at false
var count = 0; // Will count the try of the users
while (!userIsGuessing) {
var guess = prompt(hint + ' Keep guessing!'); count++; // We increment count
if(guess == x) { // CHECK IF RIGHT FIRST. EVER FOR THIS KIND OF STUFF.
userIsGuessing = true; // If right, then the Boolean come true and our loop will end.
alert("You win! It took you" + count + " times to guess the number.");
}
if (guess < x && (x - guess) < 15) hint = ' A little too small!';
else if (guess < x && (x - guess) >= 15) hint = ' Way too small!';
else if (guess > x && (x - guess) < 15) hint = ' A little too big!';
else if (guess > x && (x - guess) >= 15) hint = ' Way too big!';
}