我想做一个数学游戏,随机生成数字和运算符。
这是提示- x = Math.floor(Math.random()*101);将生成一个0到100之间的随机数。(+,*,-)为每个方程式随机选择运算符。请任何人可以帮助我。
var arr = []
while(arr.length < 8){
var r = Math.floor(Math.random()*100) + 1;
if(arr.indexOf(r) === -1) arr.push(r);
}
document.write(arr);Run Code Online (Sandbox Code Playgroud)
这是ES6的实现,我console.log代替了document.write
let questionsCount = 10;
function generateQuestions() {
let questions = [];
for(let i = 0;i < questionsCount;i++) {
let n1 = Math.floor(Math.random() * 101);
let n2 = Math.floor(Math.random() * 101);
let operatorObj = randomOperator(n1,n2)
questions.push({
question: `${n1} ${operatorObj.operator} ${n2} ?`,
answer: operatorObj.answer
});
}
return questions;
}
function randomOperator(n1,n2) {
let n = Math.floor(Math.random() * 4);
switch (n) {
case 0:
return {operator: '+', answer: n1 + n2};
case 1:
return {operator: '-', answer: n1 - n2}
case 2:
return {operator: '*', answer: n1 * n2}
case 3:
return {operator: '/', answer: n1 / n2}
}
}
let questions = generateQuestions();
let answers = questions.map((question) =>
prompt(question.question));
answers.forEach((answer,i) => {
console.log(`${questions[i].question} ${answer} ${(answer ==
questions[i].answer) ? 'Correct': `Wrong should be
${questions[i].answer}`}`)
});Run Code Online (Sandbox Code Playgroud)