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

C 프로그래밍: 구조체를 활용해 원의 넓이와 원기둥의 표면적·부피 계산하기

C 프로그래밍에서는 구조체(structure)를 활용하여 원의 넓이와 원기둥의 표면적, 부피를 손쉽게 계산할 수 있습니다. 구조체를 사용하면 길이, 반지름, 면적, 부피처럼 서로 관련된 데이터를 하나의 단위로 묶어 관리할 수 있어 코드가 더욱 체계적이고 가독성이 높아집니다.

핵심 계산 로직

1. 원의 넓이

s.areacircle = (float)pi*s.radius*s.radius;

반지름의 제곱에 원주율(pi)을 곱하여 원의 넓이를 구합니다.

2. 원기둥의 표면적

s.areacylinder = (float)2*pi*s.radius*s.line + 2 * s.areacircle;

옆면의 넓이(둘레 × 높이)에 위아래 원 2개의 넓이를 더해 전체 겉넓이를 구합니다.

3. 원기둥의 부피

s.volumecylinder = s.areacircle*s.line;

밑면(원)의 넓이에 높이를 곱하여 부피를 구합니다.

알고리즘

구조체를 활용해 원의 넓이와 원기둥의 표면적, 부피 등을 구하는 절차는 다음과 같습니다.

  1. 1단계 – 구조체 멤버를 선언합니다.
  2. 2단계 – 입력 변수를 선언하고 초기화합니다.
  3. 3단계 – 원기둥의 높이와 반지름을 입력받습니다.
  4. 4단계 – 원의 넓이를 계산합니다.
  5. 5단계 – 원기둥의 표면적을 계산합니다.
  6. 6단계 – 원기둥의 부피를 계산합니다.

예제 코드

다음은 구조체를 사용하여 원의 넓이와 원기둥의 표면적, 부피를 구하는 C 프로그램입니다.

#include<stdio.h>
struct shape{
    float line;            // 높이(길이)
    float radius;          // 반지름
    float areacircle;      // 원의 넓이
    float areacylinder;    // 원기둥의 표면적
    float volumecylinder;  // 원기둥의 부피
};
int main(){
    struct shape s;
    float pi = 3.14;
    // 사용자로부터 입력 받기
    printf("Enter a length of line or height : ");
    scanf("%f",&s.line);
    printf("Enter a length of radius : ");
    scanf("%f",&s.radius);
    // 원의 넓이 계산
    s.areacircle = (float)pi*s.radius*s.radius;
    printf("Area of circular cross-section of cylinder : %.2f\n",s.areacircle);
    // 원기둥의 표면적 계산
    s.areacylinder = (float)2*pi*s.radius*s.line + 2 * s.areacircle;
    printf("Surface area of cylinder : %.2f\n", s.areacylinder);
    // 원기둥의 부피 계산
    s.volumecylinder = s.areacircle*s.line;
    printf("volume of cylinder : %.2f\n", s.volumecylinder);
    return 0;
}

실행 결과

위 프로그램을 실행하면 다음과 같은 결과가 출력됩니다.

Enter a length of line or height: 34
Enter a length of radius: 2
Area of circular cross-section of cylinder: 12.56
Surface area of cylinder: 452.16
volume of cylinder : 427.04

높이 34, 반지름 2를 입력한 경우 원의 넓이는 12.56, 원기둥의 표면적은 452.16, 부피는 427.04로 계산되는 것을 확인할 수 있습니다. 이처럼 구조체를 활용하면 여러 계산 결과를 하나의 객체에서 깔끔하게 관리할 수 있습니다.