javascript - 将静态问题转化为动态问题

标签 javascript math random

我有如下静态问题。我在博客中使用这些问题进行测验。

var quiz = {
    "data": [
        {
            "question": "What is 10 + 5 ?",
            "answer": "15",
        },
        {
            "question": "What is 10 - 5 ?",
            "answer": "5",
        },
        {
            "question": "What is 10 + (- 5) ?",
            "answer": "5",
        },
        {
            "question": "What is -10 + 5 ?",
            "answer": "-5",
        },
        {
            "question": "What is -6 + (-6) ?",
            "answer": "-12",
        },
    ]
}

如何使问题和答案动态化?换句话说,每个数字将取 1 到 20 之间的值。答案将根据问题计算出来。

谢谢

最佳答案

function generateQuestion(template, min, max){
  // Generate first random number
  var numOne = Math.floor(Math.random() * (max - min) ) + min;
  // Generate second random number
  var numTwo = Math.floor(Math.random() * (max - min) ) + min;
  
  // append first question part
  var question = template[0];
  // check if first number is negative to put brackets around the string
  if(numOne < 0 )
    question += "(" + numOne + ")";
  else
    question +=  numOne;
   
  // append operator
  question += " + ";
  
  // check if second number is negative to put brackets around the string
   if(numTwo < 0 )
    question += "(" + numTwo + ")";
  else
    question +=  numTwo;
    
  // append last part of question
  question += template[1];
    
    
  // return your object
  return {
    question: question, 
    answer: numOne + numTwo
  };
}

var numberOfQuestions = 4;
var questions = [];
for(var i = 0; i < numberOfQuestions; i++)
  questions.push(generateQuestion(["What is ", "?"], -20, 20))
  
  
console.log(questions);

关于javascript - 将静态问题转化为动态问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58257671/

相关文章:

javascript - 如何将符号或文本放入图像的单击位置

python - 随机模块不工作。值错误 : empty range for randrange() (1, 1、0)

javascript - 如何使用 Node 中的 Promises 同时执行并行异步多个请求

javascript - 在javascript中声明一个const变量而不进行初始化

java - 使用java图形沿着圆弧路径移动对象

javascript - 我如何提出评级算法/方程式?

c - C中rand()/srand()函数是如何实现的

c# - 如何在 C# 程序中生成一组随机字符串,以便不轻易预测它们?

javascript - 如何使用 JQuery .toggle() 为 div 百分比宽度设置动画

algorithm - 重复 T(n) = T(n^(1/2)) + 1