Home > Net >  Herons formula in javascript and html
Herons formula in javascript and html

Time:06-28

I have to find the areas of a triangle using Heron's formula. I wrote this code but it is not calculating the area correctly.
For example I input sideA= 5, sideB= 4, sideC= 3 and the answer is supposed to be 6 but instead I get 72088

Can anybody help me fix this and explain why its happening?

function Triangle(sideA, sideB, sideC) {
  this.sideA = sideA;
  this.sideB = sideB;
  this.sideC = sideC;
  this.semiP = ((this.sideA   this.sideB   this.sideC) / 2);

  this.area = function() {
    return (Math.sqrt(this.semiP * ((this.semiP - this.sideA) * (this.semiP - this.sideB) * (this.semiP - this.sideC))));
  }

}

function calculate() {
  var sideA = document.getElementById('sideA').value;
  var sideB = document.getElementById('sideB').value;
  var sideC = document.getElementById('sideC').value;
  var myTriangle = new Triangle(sideA, sideB, sideC);
  document.getElementById('results').innerHTML = "Area: "   myTriangle.area();
}
<p>
  Enter length of side a <input type='text' id="sideA" />
  <br>
  <br> Enter length of side b <input type='text' id="sideB" />
  <br>
  <br> Enter length of side c <input type='text' id="sideC" />

  <div id="results"></div>

  <button type="button" onclick="calculate()">Calculate</button>

CodePudding user response:

The problem that you are having is the sideA, B and C variables are all of type STRINGs and not anything numeric. There are a few different solutions, in my answer I chose to use parseFloat to allow you to have decimal points as input as well as whole numbers.

function Triangle(sideA, sideB, sideC) {
  this.sideA = parseFloat(sideA);
  this.sideB = parseFloat(sideB);
  this.sideC = parseFloat(sideC);
  this.semiP = ((this.sideA   this.sideB   this.sideC) / 2);

  this.area = function() {
    return (Math.sqrt(this.semiP * ((this.semiP - this.sideA) * (this.semiP - this.sideB) * (this.semiP - this.sideC))));
  }

}

function calculate() {
  var sideA = document.getElementById('sideA').value;
  var sideB = document.getElementById('sideB').value;
  var sideC = document.getElementById('sideC').value;
  var myTriangle = new Triangle(sideA, sideB, sideC);
  document.getElementById('results').innerHTML = "Area: "   myTriangle.area();
}
<p>
  Enter length of side a <input type='text' id="sideA" />
  <br>
  <br> Enter length of side b <input type='text' id="sideB" />
  <br>
  <br> Enter length of side c <input type='text' id="sideC" />

  <div id="results"></div>

  <button type="button" onclick="calculate()">Calculate</button>

  • Related