let currentQuestionIndex = 0;
const questions = [];
function addOrSubtract(num1, num2, operator) {
return operator === '+' ? num1 + num2 : Math.max(0, num1 - num2); // 使用Math.max确保结果不为负
}
function displayQuestion(question) {
document.getElementById('question').textContent = question;
}
function generateQuestion() {
const operators = ['+', '-'];
let question = '';
for (let i = 0; i < 3; i++) {
const number = Math.floor(Math.random() * 4) + 1; // 1-4的随机数
const operator = i < 2 ? operators[Math.floor(Math.random() * 2)] : '';
// 立即更新问题显示
displayQuestion(question += operator + number);
if (operator !== '') { // 如果有运算符,添加空格
displayQuestion(question += ' ');
}
setTimeout(() => {
// 在这里计算答案,因为我们需要当前的问题字符串
const answer = addOrSubtract(addOrSubtract(questions[questions.length - 1] ? questions[questions.length - 1].answer : 0, parseInt(number), operator), number, operator);
questions.push({ question: question, answer: answer.toString() });
// 只在最后一轮结束后清空问题显示
if (i === 2) {
displayQuestion('');
}
}, (i + 1) * 1000);
}
}
function checkAnswer() {
const userAnswer = parseInt(document.getElementById('answerInput').value);
if (userAnswer === questions[currentQuestionIndex].answer) {
alert('正确!');
} else {
alert('错误,正确答案是: ' + questions[currentQuestionIndex].answer);
}
document.getElementById('answerInput').value = '';
if (currentQuestionIndex < 2) {
currentQuestionIndex++;
document.getElementById('question').textContent = '';
generateQuestion();
} else {
alert('所有题目已完成!');
}
}
// 初始化第一题
generateQuestion();
="100%" border="0" cellpadding="0" cellspacing="0">
="STYLE2">
="60" align="center" style="font-size: 50px; line-height: 60px; padding-top: 15px;">="question">
="STYLE2">
="150" align="center" style="font-size: 20px; line-height: 30px;">="text" id="answerInput" placeholder="输入答案">
="STYLE2">
="300" align="center">
下面是原来的generateQuestion()函数,结果会为负数,但还能显示数字,为了结果不为负数,改成上面generateQuestion()函数后,怎么一个数字都不显示了?
function generateQuestion() {
const operators = ['+', '-'];
let question = '';
for (let i = 0; i < 3; i++) {
const number = Math.floor(Math.random() * 4) + 1; // 1-4的随机数
const operator = i < 2 ? operators[Math.floor(Math.random() * 2)] : '';
setTimeout(() => {
document.getElementById('question').textContent = number + (i < 2 ? operator : '');
}, (i + 1) * 1000);
question += number + (i < 2 ? operator : '');
}
questions.push({ question: question, answer: eval(question) });
}
