An interface is a promise: every class that implements it has an area() method, so you can treat different shapes alike.
What to build
A program that calculates the area of different shapes.
Requirements
- Write an interface
Shapewitharea(): floatand the classesRect(width, height),Square(side),Circle(radius) andTriangle(base, height). - Read n, then n lines:
rect W H,square S,circle Rortriangle B H. Print each area with two decimals, thenTotal: Twith the sum of all areas, also with two decimals.
Input
Line 1: n. Then n lines.
Output
n + 1 lines.
Constraints
1 ≤ n ≤ 20; sizes are integers from 1 to 100; every line has a valid shape.
Example
Input:
3
rect 3 4
circle 1
triangle 6 5
Output:
12.00
3.14
15.00
Total: 30.14
Why it works
The loop only knows the Shape interface, so a new shape needs a new class and no change in the loop.
Examples
Example 1 · Input
3 rect 3 4 circle 1 triangle 6 5
Expected output
12.00 3.14 15.00 Total: 30.14
Example 2 · Input
1 square 7
Expected output
49.00 Total: 49.00
Hints
Hint 1
interface Shape { public function area(): float; } and one class per shape.
Hint 2
M_PI is PHP's value of pi; print areas with printf("%.2f").
Solution
Show one correct solution (try it yourself first)
<?php
interface Shape
{
public function area(): float;
}
class Rect implements Shape
{
public function __construct(protected float $w, protected float $h)
{
}
public function area(): float
{
return $this->w * $this->h;
}
}
class Square extends Rect
{
public function __construct(float $s)
{
parent::__construct($s, $s);
}
}
class Circle implements Shape
{
public function __construct(private float $r)
{
}
public function area(): float
{
return M_PI * $this->r * $this->r;
}
}
class Triangle implements Shape
{
public function __construct(private float $b, private float $h)
{
}
public function area(): float
{
return $this->b * $this->h / 2;
}
}
$n = (int) trim(fgets(STDIN));
$shapes = [];
for ($i = 0; $i < $n; $i++) {
$p = explode(" ", trim(fgets(STDIN)));
$shapes[] = match ($p[0]) {
"rect" => new Rect((float) $p[1], (float) $p[2]),
"square" => new Square((float) $p[1]),
"circle" => new Circle((float) $p[1]),
"triangle" => new Triangle((float) $p[1], (float) $p[2]),
};
}
$total = 0.0;
foreach ($shapes as $s) {
printf("%.2f\n", $s->area());
$total += $s->area();
}
printf("Total: %.2f\n", $total);