给定一个三角形的边,任务是求出该三角形的面积。
例如:
输入:a = 5, b = 7, c = 8
输出:三角形面积为 17.320508
输入:a = 3, b = 4, c = 5
输出:三角形面积为 6.000000
方法:可以使用以下公式简单地计算 三角形的面积。
其中 a、b 和 c 是三角形边长,
s = (a+b+c)/2
下面是上述方法的实现:
<?php
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 or $b < 0 or
$c < 0 or ($a + $b <= $c) or
$a + $c <= $b or $b + $c <= $a)
{
echo "Not a valid triangle";
exit(0);
}
$s = ($a + $b + $c) / 2;
return sqrt($s * ($s - $a) *
($s - $b) * ($s - $c));
}
// Driver Code
$a = 3.0;
$b = 4.0;
$c = 5.0;
echo "Area is ", findArea($a, $b, $c);
// This code is contributed anuJ_67.
?>
输出
面积为 6
时间复杂度: O(log 2 n)
辅助空间: O(1),因为没有占用额外空间。
给定一个三角形顶点的坐标,任务是找到该三角形的面积。
方法:如果给定三个角的坐标,我们可以对下面的区域 应用鞋带公式。
<?php
// PHP 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
$area = 0.0;
// Calculate value of
// shoelace formula
$j = $n - 1;
for ( $i = 0; $i < $n; $i++)
{
$area += ($X[$j] + $X[$i]) *
($Y[$j] - $Y[$i]);
// j is previous vertex to i
$j = $i;
}
// Return absolute value
return abs($area / 2.0);
}
// Driver Code
$X = array(0, 2, 4);
$Y = array(1, 3, 7);
$n = count($X);
echo polygonArea($X, $Y, $n);
// This code is contributed by anuj_67.
?>
输出
2
时间复杂度: O(n)
辅助空间: O(1)