Bài tập: Hình học với interface
Driver đã khai báo:
type Shape interface {
Area() int
Perimeter() int
}Hãy:
- Viết method
Area()vàPerimeter()choRect{W, H int}vàSquare{Side int}. - Viết
func totalArea(shapes []Shape) inttrả về tổng diện tích.
Input: dòng đầu là n, sau đó n dòng rect W H hoặc square S. Output: mỗi hình in diện_tích chu_vi, cuối cùng in total <tổng>.
Input Output
2 12 14
rect 3 4 25 20
square 5 total 37NOTE
Bạn chỉ viết phần code trong khung soạn thảo — package main, hàm main đọc input/in kết quả đã có sẵn. Các package đã import: fmt. Không thêm import khác.
Examples
Example 1
Input
2 rect 3 4 square 5
Expected output
12 14 25 20 total 37
Example 2
Input
0
Expected output
total 0
2 hidden tests · Limit 2 s · 256 MB
type Rect struct {
W, H int
}
type Square struct {
Side int
}
// TODO: hoàn thiện các method dưới đây
func (r Rect) Area() int { return 0 }
func (r Rect) Perimeter() int { return 0 }
func (s Square) Area() int { return 0 }
func (s Square) Perimeter() int { return 0 }
func totalArea(shapes []Shape) int {
// TODO
return 0
}
Comments