如何在 Javascript 中创建数学上正确且可接受的除法

对于 exp,该代码并不总是创建数学上正确的除法。它创建诸如 2/0 等的除法,并且也不接受“1/3”四舍五入的答案,如“0.33”或“0.33333”。我需要在代码中更改什么?感谢您的帮助和时间。


document.getElementById("button1").addEventListener("click", question);


var mulDiv = document.getElementById("mulDiv");


function question()

{

var startButton = document.getElementById("button1");

var number1 = document.getElementById("number1");

var number2 = document.getElementById("number2");

var decider = Math.random();

    

button1.textContent = "New Question";

number1.textContent = Math.floor(Math.random()*5);

number2.textContent = Math.floor(Math.random()*5);

    


mulDiv.textContent = "/"  


};


document.getElementById("button2").addEventListener("click", answer);



function answer()

{

var num1 = parseInt(document.getElementById("number1").textContent, 10);

var num2 = parseInt(document.getElementById("number2").textContent, 10);

var answer = parseInt(document.getElementById("userAnswer").value, 10);

var feedBack = document.getElementById("feedBack");

    

     

if (mulDiv.textContent == "/"){

if(answer == num1 / num2) {

feedBack.textContent = "right";


} else {

feedBack.textContent = "wrong";

}

}

        

};

<button id = "button1">

Start

</button>


<p>

<label id = "number1"> </label>

<label id = "mulDiv"> </label>

<label id = "number2"> </label>

 = <input id = "userAnswer" type=text>

<button id = "button2">Answer</button>

</p>


<p id = "feedBack"> </p>


智慧大石
浏览 71回答 1
1回答

慕桂英4014372

这行代码:number2.textContent&nbsp;=&nbsp;Math.floor(Math.random()*5);生成 0 到 4 之间的随机数,因为Math.random()返回 0 到 1 之间的数字(不包括 1)。你应该做:number2.textContent&nbsp;=&nbsp;1&nbsp;+&nbsp;Math.floor(Math.random()*4);这样最小值将为 1,最大值将为 5。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Html5