我已经制作了一个网页并使用JavaScript来询问5个数学问题,但是我想编辑我的代码以便能够使用随机数生成问题。我确定我打算使用Math.random功能,但我不太确定。这是我目前的代码:
<!DOCTYPE html>
<html>
<body>
<h1>A Simple Maths Game!</h1>
<p>Welcome to an awesome maths game! Your aim is simple, just answer all maths questions that you see! <br> Goodluck!</p>
<script>
// Maths question 1
var userAnswer;
userAnswer = prompt("1. 4 + 5");
if (userAnswer == 9){
document.write("1. 4 + 5 = <span class = 'correct'" + userAnswer + "</span> correct");
// document.write("\n");
document.write("<br>");
}
else{
document.write("1. 4 + 5 = <span class = 'incorrect'" + userAnswer + "</span> incorrect");
document.write("<br>");
}
// Maths question 2
var userAnswer;
userAnswer = prompt("2. 19 + 4");
if (userAnswer == 23){
document.write("2. 19 + 4 = <span class = 'correct'" + userAnswer + "</span> correct");
document.write("<br>");
}
else{
document.write("2. 19 + 4 = <span class = 'incorrect'" + userAnswer + "</span> incorrect");
document.write("<br>");
}
// Maths question 3
var userAnswer;
userAnswer = prompt("3. 5 x 5");
if (userAnswer == 25){
document.write("3. 5 x 5 = <span class = 'correct'" + userAnswer + "</span> correct");
document.write("<br>");
}
else{
document.write("3. 5 x 5 = <span class = 'incorrect'" + userAnswer + "</span> incorrect");
document.write("<br>");
}
// Maths question 4
var userAnswer;
userAnswer = prompt("4. 7 x 5");
if (userAnswer == 35){
document.write("4. 7 x 5 = <span class = 'correct'" + userAnswer + "</span> correct");
document.write("<br>");
}
else{
document.write("4. 7 x 5 = <span class = 'incorrect'" + userAnswer + "</span> incorrect");
document.write("<br>");
}
// Maths question 5
var userAnswer;
userAnswer = prompt("5. 8 x 8");
if (userAnswer == 64){
document.write("5. 8 x 8 = <span class = 'correct'" + userAnswer + "</span> correct");
document.write("<br>");
}
else{
document.write("5. 8 x 8 = <span class = 'incorrect'" + userAnswer + "</span> incorrect");
document.write("<br>");
}
</script>
</html>
提前致谢,我感谢任何帮助。
答案 0 :(得分:2)
您可以生成随机数,进行数学运算以获得您期望的答案,然后将您的预期答案与用户的实际答案进行比较:
var a = Math.floor(Math.random() * 10); // A number between 0 and 10
var b = Math.floor(Math.random() * 10); // Another number between 0 and 10
var expectedAnswer = a + b;
var answer = prompt(a + " + " + b);
if (answer == expectedAnswer)
alert('Good job !');
else
alert('Wrong answer :()');
当然这是一个只添加了一个简单的样本,但你可以更进一步,使用相同的随机系统来选择像减法等操作......