Different shapes answer the same question, how big are you, in their own way.
What to build
A program that prints the area of shapes given by name.
Requirements
- Define an interface
Shapewith anArea() float64method and three types that satisfy it. - Read n, then n shapes:
rect W H,square Sortriangle B H(base and height). All numbers are whole numbers. - Print the area of each shape with one decimal.
Input
Line 1: n. Then n lines, each a shape.
Output
n lines.
Constraints
1 ≤ n ≤ 30; every number is between 1 and 1000.
Example
Input:
3
rect 3 4
square 5
triangle 3 5
Output:
12.0
25.0
7.5
Why it works
Every shape type has an Area method, so a []Shape slice can hold them together, and the printing loop does not need to know which kind it is looking at.
Examples
Example 1 · Input
3 rect 3 4 square 5 triangle 3 5
Expected output
12.0 25.0 7.5
Example 2 · Input
2 triangle 1 1 rect 10 1
Expected output
0.5 10.0
Hints
Hint 1
Declare type Shape interface { Area() float64 } and one struct type for each kind.
Hint 2
Read the kind first, then the numbers that kind needs.
Solution
Show one correct solution (try it yourself first)
package main
import "fmt"
type Shape interface {
Area() float64
}
type Rect struct {
W, H float64
}
type Square struct {
S float64
}
type Triangle struct {
B, H float64
}
func (r Rect) Area() float64 { return r.W * r.H }
func (s Square) Area() float64 { return s.S * s.S }
func (t Triangle) Area() float64 { return t.B * t.H / 2 }
func main() {
var n int
fmt.Scan(&n)
shapes := []Shape{}
for i := 0; i < n; i++ {
var kind string
fmt.Scan(&kind)
switch kind {
case "rect":
var w, h float64
fmt.Scan(&w, &h)
shapes = append(shapes, Rect{w, h})
case "square":
var s float64
fmt.Scan(&s)
shapes = append(shapes, Square{s})
case "triangle":
var b, h float64
fmt.Scan(&b, &h)
shapes = append(shapes, Triangle{b, h})
}
}
for _, s := range shapes {
fmt.Printf("%.1f\n", s.Area())
}
}