Computer >> 컴퓨터 >  >> 프로그래밍 >> C 프로그래밍

switch-case 문으로 기하학적 도형의 넓이를 구하는 C 프로그램

문제 개요

이 글에서는 switch-case 문을 활용하여 직사각형, 정사각형, 삼각형, 원의 넓이를 계산하는 C 프로그램을 다룹니다.

사용자는 프로그램 실행 시 도형 코드를 선택하고, 해당 도형에 필요한 값(밑변, 높이, 한 변의 길이, 반지름, 폭, 길이 등)을 직접 입력하면 각 기하학적 도형의 넓이가 자동으로 계산됩니다.

해결 방법 및 공식

switch-case 문으로 각 도형별 넓이를 구하는 핵심 공식은 다음과 같습니다.

  • 직사각형의 넓이 = 폭 × 길이
  • 정사각형의 넓이 = 한 변 × 한 변
  • 의 넓이 = 3.142 × 반지름 × 반지름
  • 삼각형의 넓이 = 0.5 × 밑변 × 높이

C 프로그램 예제

다음은 switch-case 문을 사용하여 직사각형, 정사각형, 삼각형, 원의 넓이를 구하는 전체 C 프로그램입니다.

#include <stdio.h>
void main(){
    int fig_code;
    float side, base, length, breadth, height, area, radius;
    printf("-------------------------\n");
    printf(" 1 --> Circle\n");
    printf(" 2 --> Rectangle\n");
    printf(" 3 --> Triangle\n");
    printf(" 4 --> Square\n");
    printf("-------------------------\n");
    printf("Enter the Figure code\n");
    scanf("%d", &fig_code);
    switch(fig_code){
        case 1:
            printf(" Enter the radius\n");
            scanf("%f",&radius);
            area=3.142*radius*radius;
            printf("Area of a circle=%f\n", area);
            break;
        case 2:
            printf(" Enter the breadth and length\n");
            scanf("%f %f",&breadth, &length);
            area=breadth *length;
            printf("Area of a Rectangle=%f\n", area);
            break;
        case 3:
            printf(" Enter the base and height\n");
            scanf("%f %f", &base, &height);
            area=0.5 *base*height;
            printf("Area of a Triangle=%f\n", area);
            break;
        case 4:
            printf(" Enter the side\n");
            scanf("%f", &side);
            area=side * side;
            printf("Area of a Square=%f\n", area);
            break;
        default:
            printf(" Error in figure code\n");
            break;
    }
}

프로그램 동작 원리

  1. 먼저 메뉴 화면에 도형 코드(1~4)를 출력하여 사용자에게 선택지를 보여줍니다.
  2. scanf()로 사용자가 입력한 도형 코드를 fig_code 변수에 저장합니다.
  3. switch(fig_code) 문이 입력값에 따라 해당 case로 분기합니다.
  4. 각 case에서는 필요한 치수를 추가로 입력받고, 위의 공식에 대입하여 넓이를 계산한 뒤 결과를 출력합니다.
  5. 1~4 이외의 값이 입력되면 default 문이 실행되어 오류 메시지를 표시합니다.

실행 결과

위 프로그램을 실행하면 다음과 같은 결과를 얻을 수 있습니다.

Run 1:
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
3
Enter the base and height
4
7

Area of a Triangle=14.000000

Run 2:
-------------------------
1 --> Circle
2 --> Rectangle
3 --> Triangle
4 --> Square
-------------------------
Enter the Figure code
1
Enter the radius
8
Area of a circle=201.087997

첫 번째 실행에서는 밑변 4, 높이 7인 삼각형의 넓이인 14.0이 출력되었고, 두 번째 실행에서는 반지름 8인 원의 넓이 약 201.09가 출력된 것을 확인할 수 있습니다.