Last active
March 28, 2023 14:06
-
-
Save mahype/20a5424ff47aafc63b1b82877fe992a2 to your computer and use it in GitHub Desktop.
Surface Calculator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?php | |
| class SurfaceCalculator { | |
| public function calculatePolygonArea($points) { | |
| $num_points = count($points); | |
| if ($num_points < 3) { | |
| throw new InvalidArgumentException("A polygon must have at least 3 points."); | |
| } | |
| $area = 0; | |
| for ($i = 0; $i < $num_points; $i++) { | |
| $next_index = ($i + 1) % $num_points; | |
| $area += ($points[$i]['x'] * $points[$next_index]['y']) - ($points[$next_index]['x'] * $points[$i]['y']); | |
| } | |
| return abs($area) / 2; | |
| } | |
| public function calculateTriangleArea($base, $height) { | |
| return 0.5 * $base * $height; | |
| } | |
| public function calculateHeronTriangleArea($a, $b, $c) { | |
| $s = ($a + $b + $c) / 2; | |
| return sqrt($s * ($s - $a) * ($s - $b) * ($s - $c)); | |
| } | |
| public function calculateRectangleArea($length, $width) { | |
| return $length * $width; | |
| } | |
| public function calculateCircleArea($radius) { | |
| return pi() * pow($radius, 2); | |
| } | |
| public function calculateTrapezoidArea($a, $b, $height) { | |
| return 0.5 * ($a + $b) * $height; | |
| } | |
| public function calculateEllipseArea($a, $b) { | |
| return pi() * $a * $b; | |
| } | |
| } | |
| // Example usage: | |
| $surface_calculator = new SurfaceCalculator(); | |
| $polygon = [ | |
| ['x' => 0, 'y' => 0], | |
| ['x' => 4, 'y' => 0], | |
| ['x' => 4, 'y' => 4], | |
| ['x' => 0, 'y' => 4], | |
| ]; | |
| echo "The area of the polygon is: " . $surface_calculator->calculatePolygonArea($polygon) . "\n"; | |
| echo "The area of the triangle is: " . $surface_calculator->calculateTriangleArea(4, 3) . "\n"; | |
| echo "The area of the Heron's triangle is: " . $surface_calculator->calculateHeronTriangleArea(3, 4, 5) . "\n"; | |
| echo "The area of the rectangle is: " . $surface_calculator->calculateRectangleArea(4, 5) . "\n"; | |
| echo "The area of the circle is: " . $surface_calculator->calculateCircleArea(3) . "\n"; | |
| echo "The area of the trapezoid is: " . $surface_calculator->calculateTrapezoidArea(3, 5, 4) . "\n"; | |
| echo "The area of the ellipse is: " . $surface_calculator->calculateEllipseArea(3, 5) . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment