给定一个三角形的边,任务是求出该三角形的面积。
例如:
输入:a = 5, b = 7, c = 8
输出:三角形面积为 17.320508
输入:a = 3, b = 4, c = 5
输出:三角形面积为 6.000000
方法:可以使用以下公式简单地计算 三角形的面积。
其中 a、b 和 c 是三角形边长,
s = (a+b+c)/2
下面是上述方法的实现:
// javascript Program to find the area
// of triangle
function findArea( a, b, c)
{
// Length of sides must be positive
// and sum of any two sides
// must be smaller than third side.
if (a < 0 || b < 0 || c < 0 ||
(a + b <= c) || a + c <= b ||
b + c <= a)
{
document.write( "Not a valid triangle");
return;
}
let s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) *
(s - b) * (s - c));
}
// Driver Code
let a = 3.0;
let b = 4.0;
let c = 5.0;
document.write( "Area is " + findArea(a, b, c));
// This code is contributed by todaysgaurav
输出
面积为 6
时间复杂度: O(log 2 n)
辅助空间: O(1),因为没有占用额外空间。
给定一个三角形顶点的坐标,任务是找到该三角形的面积。
方法:如果给定三个角的坐标,我们可以对下面的区域 应用鞋带公式。
// Javascript program to evaluate area of a polygon using
// shoelace formula
// (X[i], Y[i]) are coordinates of i'th point.
function polygonArea(X, Y, n)
{
// Initialize area
let area = 0.0;
// Calculate value of shoelace formula
let j = n - 1;
for (let i = 0; i < n; i++)
{
area += (X[j] + X[i]) * (Y[j] - Y[i]);
j = i; // j is previous vertex to i
}
// Return absolute value
return Math.abs(area / 2.0);
}
// Driver program to test above function
let X = [0, 2, 4];
let Y = [1, 3, 7];
let n = X.length;
document.write(polygonArea(X, Y, n));
// This code is contributed by Mayank Tyagi
输出
2
时间复杂度: O(n)
辅助空间: O(1)