Program JavaScript untuk Menghitung Luas Segitiga

Jika Anda mengetahui alas dan tinggi segitiga, Anda dapat mencari luasnya menggunakan rumus:

area = (base * height) / 2

Contoh 1: Area Ketika Basis dan Tinggi Diketahui

const baseValue = prompt('Enter the base of a triangle: ');
const heightValue = prompt('Enter the height of a triangle: ');

// calculate the area
const areaValue = (baseValue * heightValue) / 2;

console.log(
  `The area of the triangle is ${areaValue}`
);

Keluaran

Enter the base of a triangle: 4
Enter the height of a triangle: 6
The area of the triangle is 12

Jika Anda mengetahui semua sisi segitiga, Anda dapat mencari luasnya menggunakan rumus Herons. Jika a, b dan c adalah tiga sisi segitiga, lalu

s = (a+b+c)/2
area = √(s(s-a)*(s-b)*(s-c))

Contoh 2: Area Ketika Semua Sisi Diketahui

// JavaScript program to find the area of a triangle

const side1 = parseInt(prompt('Enter side1: '));
const side2 = parseInt(prompt('Enter side2: '));
const side3 = parseInt(prompt('Enter side3: '));

// calculate the semi-perimeter
const s = (side1 + side2 + side3) / 2;

//calculate the area
const areaValue = Math.sqrt(
  s * (s - side1) * (s - side2) * (s - side3)
);

console.log(
  `The area of the triangle is ${areaValue}`
);

Keluaran

Enter side1: 3
Enter side2: 4
Enter side3: 5
The area of the triangle is 6

Di sini, kami telah menggunakan Math.sqrt() metode untuk menemukan akar kuadrat dari sebuah angka.

catatan: Jika segitiga tidak dapat dibentuk dari sisi yang diberikan, program tidak akan berjalan dengan benar.