JS计算三角形的周长和面积错误

时间:2018-02-16 21:53:06

标签: javascript

这是我的第一个JS脚本。代码正在运行,但错误的答案(周长为50倍到高)。有人能帮助我吗?



function calc() {
var side1 = document.getElementById("s1").value;
var side2 = document.getElementById("s2").value;
var side3 = document.getElementById("s3").value;
var perimeter = (side1 + side2 + side3);
var area =  Math.sqrt(perimeter/2*((perimeter/2-side1)*(perimeter/2-side2)*(perimeter/2-side3)));
document.getElementById("answer1").innerHTML = "area: " + area;
document.getElementById("answer2").innerHTML = "perimeter: " + perimeter;
}

<form>
  Side 1:
  <input type="text" name="s1" id="s1" value=5><br>
  Side 2:
  <input type="text" name="s2" id="s2" value=6><br>
  Side 3:
  <input type="text" name="s3" id="s3" value=7>
</form>

<button onclick="calc()">Calculate area</button>

<p>test1</p>
<p id="answer1"></p>
<p id="answer2"></p>
&#13;
&#13;
&#13;

我刚开始编程?是HTML CSS&amp; JS一个好的开始?

2 个答案:

答案 0 :(得分:1)

document.getElementById("s1").value是一个字符串,因此side1 + side2 + side3是字符串连接,而不是sum。稍后,当您将perimeter除以2时,它将转换为数字。您可以通过在其前面添加+将每个字符串转换为数字。

+unary operator,可将其操作数转换为数字。一元加号是将某些东西转换为数字的最快和首选方式,因为它不对该数字执行任何其他操作。

function calc() {
    var side1 = +document.getElementById("s1").value;
    var side2 = +document.getElementById("s2").value;
    var side3 = +document.getElementById("s3").value;
    var perimeter = (side1 + side2 + side3);
    var area =  Math.sqrt(perimeter/2*((perimeter/2-side1)*(perimeter/2-side2)*(perimeter/2-side3)));
    document.getElementById("answer1").innerHTML = "area: " + area;
    document.getElementById("answer2").innerHTML = "perimeter: " + perimeter;
}
<form>
  Side 1:
  <input type="text" name="s1" id="s1" value=5><br>
  Side 2:
  <input type="text" name="s2" id="s2" value=6><br>
  Side 3:
  <input type="text" name="s3" id="s3" value=7>
</form>

<button onclick="calc()">Calculate area</button>

<p>test1</p>
<p id="answer1"></p>
<p id="answer2"></p>

答案 1 :(得分:0)

您可以在输入值上使用parseInt(),因为它们是作为字符串传递的。 你对周边的567结果显然是字符串连接

另请参阅此SO question,了解为何使用parseInt()also this one拥有更多测试用例。

function calc() {
var side1 = parseInt(document.getElementById("s1").value);
var side2 = parseInt(document.getElementById("s2").value);
var side3 = parseInt(document.getElementById("s3").value);
var perimeter = side1 + side2 + side3;
var area =  Math.sqrt(perimeter/2*((perimeter/2-side1)*(perimeter/2-side2)*(perimeter/2-side3)));
document.getElementById("answer1").innerHTML = "area: " + area;
document.getElementById("answer2").innerHTML = "perimeter: " + perimeter;
}
<form>
  Side 1:
  <input type="text" name="s1" id="s1" value=5><br>
  Side 2:
  <input type="text" name="s2" id="s2" value=6><br>
  Side 3:
  <input type="text" name="s3" id="s3" value=7>
</form>

<button onclick="calc()">Calculate area</button>

<p>test1</p>
<p id="answer1"></p>
<p id="answer2"></p>