2014-01-20 14 views
1

我想知道我們如何獲得一個隨機數學運算符來使用和處理數學測驗問題。如何獲得在javascript中的測驗qustion的隨機數學運算符

隨機問題給用戶解決,問題只有兩個數字來解決任何的加法,減法,乘法或除法。

我有這段代碼來產生兩個隨機數。

HTML

<div id="num1"></div><!--end of num1--> 
    <div id="num2"></div><!--end of num2--> 
    <div id="operator"></div><!--end of operator--> 
    <div id="answer"></div><!--end of answer--> 
    <button onclick="New()">New</button> 

的Javascript

function New(){ 
num1=document.getElementById("num1"); 
num2=document.getElementById("num2"); 
rnum1 = Math.floor((Math.random()*100)+1); 
rnum2 = Math.floor((Math.random()*100)+1); 
num1.innerHTML=rnum1 
num2.innerHTML=rnum2  
} 

我如何生成隨機接線員+ - * /代碼 使用和處理類似

operator.innerHTML = '+'; 
answer.innerHTML = rnum1 + rnum2; 

回答

3

你可以這樣做:

var operators = [{ 
     sign: "+", 
     method: function(a,b){ return a + b; } 
    },{ 
     sign: "-", 
     method: function(a,b){ return a - b; } 
    }]; 

var selectedOperator = Math.floor(Math.random()*operators.length); 

operators[selectedOperator].sign     //this will give you the sign 
operators[selectedOperator].method(rnum1, rnum2) //this will give you the answer 
+1

+1對於漂亮和安全的解決方案。謝謝。 –

2

運營商定義的數組:

var ops=['+','-','*','/']; 

//random operator 

var opindex = Math.random()*4; //good that your rnum2 cannot be zero 
var operator = ops[opindex]; 

//calculate the expected result: 

var res; 
switch (opindex){ 
    case 0: res=rnum1+rnum2; break; 
    case 1: res=rnum1-rnum2; break; 
    case 2: res=rnum1*rnum2; break; 
    case 3: res=rnum1/rnum2; break; 
} 
+0

+ 1爲好的解決方案,但作爲德里克回答第1我接受這個答案。我感謝你的時間和解決方案。 –

0

例子:

var operators = ['+','-','*','/']; 

function New(){ 
    num1=document.getElementById("num1"); 
    num2=document.getElementById("num2"); 
    oper=document.getElementById("operator"); 
    answer=document.getElementById("answer"); 
    rnum1 = Math.floor((Math.random()*100)+1); 
    rnum2 = Math.floor((Math.random()*100)+1); 
    op = operators[Math.floor(Math.random()*4)]; 
    num1.innerHTML=rnum1; 
    num2.innerHTML=rnum2; 
    oper.innerHTML=op; 
    answer.innerHTML = eval(rnum1 + op + rnum2); 
} 
+0

你不能通過這種方式來計算答案。 –

+0

你*可以*使用'eval',但它不被認爲是安全的做法。 –

+0

在這種情況下是安全的 –

0

我知道我有點遲到了,但我想我會分享一個不錯的小散我寫的地圖清楚地利用了ES6的箭頭功能。

const OPMAP = { 
    '*': (n1, n2) => n1 * n2, 
    '/': (n1, n2) => n1/n2, 
    '+': (n1, n2) => n1 + n2, 
    '-': (n1, n2) => n1 - n2 
} 

直接讓OPMAP [操作]讓你匿名函數,並OPMAP [操作](N1,N2),以獲得您的結果。

相關問題