您好,我正在创建一个简单的游戏,其中程序生成 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>
最佳答案
你的逻辑倒退了:
numri
是随机数,pergjigja
是输入。如果您输入 1001
,然后您将看到太低错误消息。
您应该更新 <
和>
运算符(operator)喜欢这样以获得所需的行为:
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();
}
关于Javascript 猜数字游戏不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48834436/