You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS随机猜数字游戏无输出问题求助(编程作业)

猜数字游戏代码问题修复

你的代码里有几个语法和逻辑错误,导致点击按钮后无输出,具体问题和修复方式如下:

  • 随机数生成逻辑错误
    Math.floor(Math.random() * 1, 101)的写法完全错误,Math.random()返回0到1(不含1)的小数,要生成1-100的随机整数,正确写法是Math.floor(Math.random() * 100) + 1——先通过Math.random() *100得到0到99.999...的数,floor后转为0-99的整数,再加1就得到1-100的范围。

  • else语句语法非法
    else (inputValue == randomNumber)是错误写法,else不能附带条件判断。因为前面的else if (inputValue != randomNumber)已经判断了"猜测数不等于随机数"的情况,剩下的自然就是相等的情况,直接写else即可。

  • 字符串拼接缺少运算符
    成功提示的字符串里,inputValue和后面的"Good job."之间缺少+连接符,导致语法报错,应该改成"You guessed correctly! Your number was " + inputValue + " Good job."。

  • 类型不匹配导致的判断失效
    输入框获取到的inputValue是字符串类型,直接和数字类型的randomNumber比较会有隐式转换问题,建议把输入值转为数字类型,比如let inputValue = Number(document.getElementById("input").value);。

  • 多余的闭合标签
    <head>标签里的</style>没有对应的开启标签,属于无效标签,直接删除即可。


修正后的完整代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Random Number Game</title>
</head>
<body>
    <div>
        <h1>Guess a random number!</h1>
        <input type="text" id="input" placeholder="Type guess here!"><br>
        <button onclick="displayOutput()">Submit</button>
        <p>Type in a number 1 - 100 in the space above and see if you were right or not.</p>
        <span id="output"></span>
    </div>

    <script>
        function displayOutput() {
            let inputValue = Number(document.getElementById("input").value);
            let randomNumber = Math.floor(Math.random() * 100) + 1;

            if (isNaN(inputValue) || inputValue <1 || inputValue >100) {
                document.getElementById("output").innerHTML = 
                    "You have to enter a valid number between 1 and 100";
            } else if (inputValue !== randomNumber) {
                document.getElementById("output").innerHTML = 
                    `Your guess was incorrect. Try again. The number was ${randomNumber}`;
            } else {
                document.getElementById("output").innerHTML = 
                    `You guessed correctly! Your number was ${inputValue}. Good job.`;
            }
        }
    </script>
</body>
</html>

(额外优化了输入验证,加入了判断是否为有效数字、是否在1-100范围内的逻辑,同时用模板字符串让拼接更清晰)

内容的提问来源于stack exchange,提问作者Brexton Appleseed

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.19 22:43:22