我正在创建一个名为guess a number的简单程序。我在显示输出时遇到问题。所以我不知道我是否得到了正确的配方。
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
<script>
function guess() {
var num = document.getElementById("number").value;
var answer = Math.floor(Math.Random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
</body>
答案 0 :(得分:2)
生成随机数时出现语法错误。
应该是
Math.random();
但你有
Math.Random();
以下是完整的代码:
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
<script>
function guess() {
var num = document.getElementById("number").value;
var answer = Math.floor(Math.random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
</body>
开发Javascript时,请始终打开浏览器的控制台。它会向你展示这个错误。所有浏览器都有控制台。
答案 1 :(得分:0)
您的代码是正确的,但您需要使用固定数字测试该函数以查看它是否有效,然后使用Math.random();
(小写random()
),在这种情况下,我使用11
作为正确的数字..
function guess() {
var num = document.getElementById("number").value;
//var answer = Math.floor(Math.random() * 100 + 1);
var answer = 11;
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
&#13;
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
</body>
&#13;
答案 2 :(得分:0)
// ---使用Math.random而不是Math.Random ------
`
<script>
function guess() {
var num = document.getElementById("number");
//alert(num);
var answer = Math.floor(Math.random() * 100 + 1);
if(num == answer)
alert("Your guess is correct! The number is" + answer);
else if(num != answer)
alert("Your guess is incorrect! The number is" + answer);
}
</script>
&#13;
<body>
<h3> Guess A Number</br> </h3><input type="integer" id="number" size="20"/>
<input type="button" id="guess" value="GUESS" onClick="guess()"/>
</body>
&#13;