用javascript编写程序,实现随机产生50以内加减法出题程序,输入计算结果,自动判断正确与否,并把每一道题都显示在页面上
时间: 2024-04-30 07:18:31 浏览: 88
以下是用JavaScript编写的实现随机产生50以内加减法出题并判断答案的程序:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>加减法出题程序</title>
</head>
<body>
<h1>加减法出题程序</h1>
<p>请根据以下题目输入答案,点击“提交”按钮判断答案是否正确。</p>
<div id="question"></div>
<input type="text" id="answer" placeholder="请输入答案">
<button onclick="checkAnswer()">提交</button>
<p id="result"></p>
<script>
// 生成随机数
function randomNum(max) {
return Math.floor(Math.random() * (max + 1));
}
// 生成加减法题目
function generateQuestion() {
var num1 = randomNum(50);
var num2 = randomNum(50);
var operator = randomNum(1);
if (operator === 0) {
return num1 + ' + ' + num2;
} else {
return num1 + ' - ' + num2;
}
}
var question = document.getElementById('question');
var answerInput = document.getElementById('answer');
var result = document.getElementById('result');
// 显示题目
question.innerHTML = generateQuestion();
// 判断答案是否正确
function checkAnswer() {
var userAnswer = parseInt(answerInput.value);
var questionText = question.innerHTML;
var questionParts = questionText.split(' ');
var num1 = parseInt(questionParts[0]);
var operator = questionParts[1];
var num2 = parseInt(questionParts[2]);
var correctAnswer;
if (operator === '+') {
correctAnswer = num1 + num2;
} else {
correctAnswer = num1 - num2;
}
if (userAnswer === correctAnswer) {
result.innerHTML = '恭喜你,答案正确!';
} else {
result.innerHTML = '很遗憾,答案错误!';
}
// 显示下一道题目
question.innerHTML = generateQuestion();
answerInput.value = '';
}
</script>
</body>
</html>
```
每次刷新页面都会随机生成一道加减法题目,用户输入答案后点击“提交”按钮,程序会自动判断答案是否正确,并将结果显示在页面上,同时还会自动生成下一道题目。
阅读全文