javascriptfunctionpythagorean

pythagorean formula to calculate the perimeter of triangle in Javascript?


i am so newbie in programming. i had problem how to count the area and around of triangle.

i had code code some, but the output results are always wrong calculate.

function fungsiLuasSegitiga(a, b) {
  var luas = (1 / 2) * a * b;
  return luas;
}

function fungsiKllSegitiga(a, b) {
  var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
  var kll = a + b + c;
  return kll;
}

var x = prompt("masukkan nilai alas segitiga!");
var y = prompt("masukkan nilai tinggi segitiga!");

var d = fungsiLuasSegitiga(x, y);
var e = fungsiKllSegitiga(x, y);

alert("luas segitiga adalah " + d);
alert("keliling segitiga adalah " + e);

when i put number 3 and 4, the function fungsiLuasSegitiga count it be 345, but the result must be 12 (3+4+5).


Solution

  • prompt returns a string and not a number. So, kll calculation ends up being "3" + "4" + 5. This concatenates the string instead of summing the numbers. You need to parse it to a number before assigning it to x and y either by using unary plus operator or parseInt

    function fungsiLuasSegitiga(a, b) {
      var luas = (1 / 2) * a * b;
      return luas;
    }
    
    function fungsiKllSegitiga(a, b) {
      var c = Math.sqrt(Math.pow(a, 2) + Math.pow(b, 2));
      var kll = a + b + c;
      return kll;
    }
    
    var x = +prompt("masukkan nilai alas segitiga!");
    var y = +prompt("masukkan nilai tinggi segitiga!");
    
    var d = fungsiLuasSegitiga(x, y);
    var e = fungsiKllSegitiga(x, y);
    
    alert("luas segitiga adalah " + d);
    alert("keliling segitiga adalah " + e);