猜数字小游戏

301 阅读1分钟

猜数字小游戏规则

  • 生成0~99的随机幸运数字(整数)
  • 让用户输入数字,直到猜对为止
  • 使用 while 循环
let num = parseInt(Math.random() * 100)

while (true) {
    let cai = parseInt(prompt('猜一猜这个数字是多少?'))
    if (cai > num) {
        alert('你猜大了,继续!')
    } else if (cai < num) {
        alert('你猜小了,继续')
    } else if (cai == num) {
        alert('恭喜你,猜对了!')
        // 使用break主动结束循环
        break
    } else {
        alert('操作有误,请重新输入!')
    }
}

猜数字小游戏规则(升级版)

  • 生成0~99的随机幸运数字(整数)
  • 让用户输入有效数字,只有三次机会
  • 使用 while 循环 或 for 循环
let num = parseInt(Math.random() * 100)

let i = 1
while (i <= 3) {
    let cai = parseInt(prompt('请输入你猜的数字?'))
    i++
    if (cai > num) {
        alert('猜大了')
    } else if (cai < num) {
        alert('猜小了')
    } else if (cai == num) {
        alert('恭喜你,猜对了')
        break
    } else {
        alert('操做有误,请重新输入!')
        i--
    }
}
alert('你的机会已经用完了')
let num = parseInt(Math.random() * 100)

for (let i = 1; i <= 3; i++) {
    let cai = parseInt(prompt('请输入你猜的数字?'))
    if (cai > num) {
        alert('猜大了')
    } else if (cai <= num) {
        alert('猜小了')
    } else if (cai == num) {
        alert('恭喜你,猜对了')
        break
    } else {
        alert('操做有误,请重新输入!')
        i--
    }
}
alert('你的机会已经用完了')