我很确定我的代码是正确的,我很确定我的公式是正确的但是出于某种原因我得到的结果是7496238.570769714,应该是14.6969。这意味着一定有什么问题......我错过了什么,亲爱的代码大师?
我搜索了论坛,发现人们做了类似的任务,但遇到了不同的问题,我使用mozilla检查我的结果。
var answer = 0;
var areaFromLength = function() {
var a = document.getElementById("a").value;
var b = document.getElementById("b").value;
var c = document.getElementById("c").value;
var x = (a + b + c) / 2;
var answer = Math.sqrt(x * ((x - a) * (x - b) * (x - c)));
document.getElementById("result").innerHTML = "<p>The area of the triangle is " + answer + "</p>";
return false;
};
&#13;
<form id="tAreas">
<p><input type="number" id="a" name="a" value="5"> length of triangle side 1</p>
<p><input type="number" id="b" name="b" value="6"> length of triangle side 2</p>
<p><input type="number" id="c" name="c" value="7"> length of triangle side 2</p>
<button onclick="return areaFromLength()">Do the maths!</button>
</form>
<div id="result">
<p>Your answer will appear here</p>
</div>
&#13;
答案 0 :(得分:1)
数学时你的数字被视为字符串(5 + 6 + 7 = 567)。使用parseFloat
:
var answer = 0;
window.areaFromLength = function() {
var a = parseFloat(document.getElementById("a").value);
var b = parseFloat(document.getElementById("b").value);
var c = parseFloat(document.getElementById("c").value);
var x = (a + b + c) / 2;
var answer = Math.sqrt(x * ((x - a) * (x - b) * (x - c)));
document.getElementById("result").innerHTML = "<p>The area of the triangle is " + answer + "</p>";
return false;
};
&#13;
<form id="tAreas">
<p><input type="number" id="a" name="a" value="5"> length of triangle side 1</p>
<p><input type="number" id="b" name="b" value="6"> length of triangle side 2</p>
<p><input type="number" id="c" name="c" value="7"> length of triangle side 2</p>
<button onclick="return areaFromLength()">Do the maths!</button>
</form>
<div id="result">
<p>Your answer will appear here</p>
</div>
&#13;