Menu
Coddy logo textTech

복습 - 도형의 넓이

Coddy R 여정의 객체 지향 프로그래밍 섹션에 포함된 레슨. 57개 중 11번째.

challenge icon

챌린지

중급

네 개의 파일로 작은 도형 라이브러리를 만드세요. 생성자는 이미 제공됩니다.

  • Shape.R: 제네릭 area(shape, ...), perimeter(shape, ...) 및 describe(shape, ...)입니다. 기본 area() 및 perimeter() 메서드는 unknown shape: hexagon으로 중단되어야 합니다(call. = FALSE 사용). 기본 describe()는 도형의 첫 번째 클래스와 두 제네릭을 사용해 만들고 소수점 이하 두 자리로 표시한 circle: area 3.14, perimeter 6.28을 반환합니다.
  • Circle.R, Rectangle.R, Triangle.R: 각 도형의 area 및 perimeter 메서드입니다. 삼각형은 a, b, c 변을 가지며, 넓이는 둘레의 절반인 s를 사용한 sqrt(s * (s - a) * (s - b) * (s - c))입니다.

제공된 코드는 circle 1, rectangle 2 3, triangle 3 4 5 또는 다른 이름을 읽고, describe() 또는 error: 와 메시지를 출력한 다음 전체 넓이를 출력합니다.

코드는 Shape.R, Circle.R, Rectangle.R 및 Triangle.R에 작성하세요. main.R에는 제공된 입출력 코드가 들어 있으며 편집할 수 없습니다.

직접 해보기

source("Shape.R")
source("Circle.R")
source("Rectangle.R")
source("Triangle.R")

# 제공된 입력/출력 코드: 그대로 유지하세요
input <- suppressWarnings(readLines(file("stdin")))
total <- 0
for (line in input) {
  p <- strsplit(line, " ")[[1]]
  n <- as.numeric(p[-1])
  s <- switch(p[1],
    circle = new_circle(n[1]),
    rectangle = new_rectangle(n[1], n[2]),
    triangle = new_triangle(n[1], n[2], n[3]),
    structure(list(), class = p[1]))
  out <- tryCatch({
    total <- total + area(s)
    describe(s)
  }, error = function(e) paste("error:", conditionMessage(e)))
  cat(out, "\n", sep = "")
}
cat(sprintf("total area: %.2f", total), "\n", sep = "")

객체 지향 프로그래밍의 모든 레슨

직접 연습해 보세요: 온라인 R 컴파일러