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

如果您知道三角形的所有边,您可以使用 海伦公式 来计算面积。如果 abc 是三角形的三条边,则

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() 方法来查找 数字的平方根

注意:如果给定的边无法构成三角形,程序将无法正确运行。


另请阅读

在我们结束之前,让我们来检验一下你对这个例子的理解!你能解决下面的挑战吗?

挑战

编写一个函数来计算三角形的面积。

  • 返回底为 base、高为 height 的三角形的面积。
  • 提示:三角形的面积公式是:area = 0.5 * base * height
  • 例如,如果 base = 10height = 5,则预期输出为 25
你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战