Javascript猜数字游戏无法正常工作

时间:2018-02-16 20:30:21

标签: javascript html

您好我正在创建一个简单的游戏,程序生成1-1000之间的随机数,然后用户输入一个数字。如果它越小它产生的太低如果它越大它产生的太高并且祝贺它是正确的。问题是我的程序总是产生太高。你可以帮帮我吗?谢谢!

<!DOCTYPE html>
 <html>
 <head>
<script type="text/javascript">
    var numri=gjenero();
    function gjenero(){
        return Math.floor(1000*Math.random())+1;
    }
    function kontrollo(){
     pergjigja=parseInt(document.getElementById("pergjigja").value);
        if (numri<pergjigja){
           alert("Too low!");
           document.getElementById("pergjigja").value="";

        }
        else if (numri>pergjigja){
            alert("Too high!");
            document.getElementById("pergjigja").value="";
        }
        else {
             alert("Congratulations.Continue the game with another 
        number!");
            gjenero();
        }
    }
   </script>
    </head>
       <body>

   <input type="text" id="pergjigja" >
   <button onclick="kontrollo();">Check</button>
  </body>
   </html>

1 个答案:

答案 0 :(得分:1)

你的逻辑向后:

numri是随机数,pergjigja是输入。如果您输入1001,那么您会看到太低错误消息。

您应该像这样更新<>运算符以获得所需的行为:

if (numri>pergjigja){
   alert("Too low!");
   document.getElementById("pergjigja").value="";

}
else if (numri<pergjigja){
    alert("Too high!");
    document.getElementById("pergjigja").value="";
}
else {
    alert("Congratulations.Continue the game with another number!");
    numri=gjenero();
}