帮助生成简单数学问题的随机数

时间:2014-02-09 01:40:02

标签: javascript random

我正在尝试编写一些会产生40个数学问题的简单代码。目标是用户在表单字段中输入数字,该数字表示任何问题的最高可能总和(例如,仅产生两个数字加起来为10或更少的问题)。单击以生成问题后,将生成随机数以创建40个数学问题。诀窍是两个数字的总和不得超过开头输入的数量。

我可以生成一个随机数,但是如果没有一些可怕的编写代码我就无法生成不同的数字而我无法弄清楚如何设置逻辑以使问题与输入的级别(即最高可能总和)相匹配用户。

任何帮助都将不胜感激。

感谢。

编辑: 有人问我有什么,这并不多。足以严重生成两个随机数:

<script>
function myFunction()
{
var x=document.getElementById("number")
x.innerHTML=Math.floor((Math.random()*10)+1);

var x=document.getElementById("number2")
x.innerHTML=Math.floor((Math.random()*10)+1);
}
</script>

<div class="row">
  <div class="span2"></div>
  <div class="span2">
  <div id="number" style="display:inline"></div>
  </div>
    <div class="span2"></div>
  <div class="span2">
  <div id="number2" style="display:inline"></div>
  </div>

3 个答案:

答案 0 :(得分:1)

这可能就足够了(或者至少是朝着正确方向迈出的一步):

function generateRandom(max) {
    return Math.floor((Math.random() * max)+1);
}

var questionIDs = [],
    quantity = 40,
    maxValueOfSum = 10,
    q=0, 
    i=0;

while(q<quantity && i<100){
    var answer = generateRandom(maxValueOfSum),
        A = generateRandom(answer),
        B = answer - A,
        id = ''+A+''+B;// < a string id for adding to our array of used questions
    if(questionIDs.indexOf(id) == -1){// if this question does not already exist
        questionIDs.push(id);//add the id to the list
        q++;//increment question count
        document.getElementById('questions').innerHTML+='<div>Q'+q+': '+A+' + '+B+' = ______</div>';//append some HTML
    }
    i++;//increment the loop counter so it doesnt continue forever in cases where it isnt possible to get [quantity] unique questions.
}

演示:http://jsfiddle.net/LjfyF/

答案 1 :(得分:0)

这应该有助于解决多个问题,并且你的约束条件是总和不超过特定的最高允许总和:

function myFunction(highest, i) {
    // The sum of two integers A and B, neither one negative,
    // is less than or equal to "highest".
    // Fill two elements, example IDs: numberA1 and numberB1 when i == 1.
    var x=document.getElementById("numberA" + i)
    n=Math.floor(Math.random()*(highest+1));
    x.innerHTML=n
    var x=document.getElementById("numberB" + i)
    x.innerHTML=Math.floor(Math.random()*(highest + 1 - n));
}

答案 2 :(得分:0)

你的意思是你想要这样做:

function getRand(max) {
  return Math.floor((Math.random() * max)+1);
}

limit=40;               // limit of the 2 numbers you want to add
answer=getRand(limit);  // get a random value for the answer
num1=getRand(answer);   // get one random number: 0 to answer
num2= answer - num1;    // calc the other number

alert("What is "+num1+" + "+num2+" ?" );