如果你知道一个三角形的底和高,你可以用下面的公式求面积:
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
如果您知道三角形的所有边,您可以使用Herons 公式求面积。如果
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()
方法来求一个数的平方根。
注意: 如果不能从给定的边形成三角形,程序将无法正确运行。