三角形の面積を計算するJavaScriptプログラム

Javascript

三角形の底辺と高さがわかっている場合は、次の式を使用して面積を見つけることができます。

area = (base * height) / 2

例1:底辺と高さがわかっている場合の面積

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}`
);

出力

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

三角形のすべての辺を知っている場合は、を使用して領域を見つけることができます ヘロンの公式。 場合 ab そして c 三角形の3つの辺であり、

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

例2:すべての側面がわかっている領域

// 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}`
);

出力

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

ここでは、 Math.sqrt() 数値の平方根を見つける方法。

注意: 指定された辺から三角形を形成できない場合、プログラムは正しく実行されません。



Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 が付いている欄は必須項目です