示例:猜数字程序
// program where the user has to guess a number generated by a program
function guessNumber() {
// generating a random integer from 1 to 10
const random = Math.floor(Math.random() * 10) + 1;
// take input from the user
let number = parseInt(prompt('Guess a number from 1 to 10: '));
// take the input until the guess is correct
while(number !== random) {
number = parseInt(prompt('Guess a number from 1 to 10: '));
}
// check if the guess is correct
if(number == random) {
console.log('You guessed the correct number.');
}
}
// call the function
guessNumber();
输出
Guess a number from 1 to 10: 1 Guess a number from 1 to 10: 8 Guess a number from 1 to 10: 5 Guess a number from 1 to 10: 4 You guessed the correct number.
注意:每次运行程序时,您都会得到不同的输出值,因为每次都会生成一个不同的数字。
在上面的程序中,创建了 guessNumber()
函数,其中使用 Math.random()
函数生成一个 1 到 10 之间的随机数。
要了解更多关于如何生成随机数的信息,请访问 JavaScript 生成随机数。
- 系统会提示用户猜测一个 1 到 10 之间的数字。
- parseInt() 将数字 字符串 值转换为整数值。
while
循环用于接受用户输入,直到用户猜对为止。- 使用
if...else
语句来检查条件。使用等于==
运算符 来检查猜测是否正确。if(number == random)
要了解更多关于比较运算符的信息,请访问 JavaScript 比较运算符。