如果您知道三角形的底和高,您可以使用该公式计算面积
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
如果您知道三角形的所有边,您可以使用 海伦公式 来计算面积。如果 a
、b
和 c
是三角形的三条边,则
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()
方法来查找 数字的平方根。
注意:如果给定的边无法构成三角形,程序将无法正确运行。
另请阅读