삼각형 면적 계산

CBeginner
지금 연습하기

소개

기하학에서 삼각형의 면적은 삼각형의 경계 내부에 있는 공간의 양으로 정의됩니다. 삼각형의 면적을 계산하는 방법에는 여러 가지가 있지만, 가장 일반적인 두 가지 방법은 삼각형의 밑변과 높이를 사용하거나, 삼각형의 세 변을 입력으로 사용하는 헤론의 공식 (Heron's formula) 을 사용하는 것입니다.

이 Lab 에서는 이러한 두 가지 방법을 모두 사용하여 C 프로그램을 작성하여 삼각형의 면적을 구하는 방법을 배우게 됩니다.

밑변과 높이를 사용한 기본 프로그램

다음 프로그램은 삼각형의 밑변과 높이를 사용하여 삼각형의 면적을 계산합니다.

#include<stdio.h>
int main()
{
    int h, b;
    float area;

    // Input height and base of the triangle
    printf("Enter the height of the Triangle: ");
    scanf("%d", &h);
    printf("Enter the base of the Triangle: ");
    scanf("%d", &b);

    // Calculate area of the triangle
    area = (h*b)/(float)2;

    // Output the area of the triangle
    printf("The area of the triangle is: %f", area);
    return 0;
}

설명:

  • 표준 입출력 함수를 위해 stdio.h 라이브러리를 포함했습니다.
  • main 함수를 정의하고 h, b, area 변수를 선언했습니다.
  • scanf 함수를 사용하여 사용자가 삼각형의 밑변과 높이를 입력하도록 했습니다.
  • 그런 다음 공식 (높이 x 밑변)/2를 사용하여 삼각형의 면적을 계산합니다.
  • area = (h*b)/(float)2는 분모 값을 int에서 float로 형변환했기 때문에 소수점 단위로 결과를 제공합니다.
  • 마지막으로 printf 함수를 사용하여 삼각형의 면적을 출력합니다.

헤론의 공식 (Heron's Formula) 을 사용한 고급 프로그램

다음 프로그램은 헤론의 공식 (Heron's formula) 을 사용하여 삼각형의 면적을 계산합니다.

#include<stdio.h>
#include<math.h>

int main()
{
    double a, b, c, area, s;

    // Input sides of the triangle
    printf("Enter the sides of the triangle:\n");
    scanf("%lf%lf%lf", &a, &b, &c);

    // Calculate s, the semi-perimeter of the triangle
    s = (a+b+c)/2;

    // Calculate area of the triangle using Heron's formula
    area = sqrt(s*(s-a)*(s-b)*(s-c));

    // Output the area of the triangle
    printf("The area of the Triangle calculated using Heron's formula is: %lf", area);
    return 0;
}

설명:

  • 표준 입출력 함수와 제곱근 함수를 위해 각각 stdio.hmath.h 라이브러리를 포함했습니다.
  • main 함수와 일부 변수가 선언되었습니다.
  • scanf 함수를 사용하여 삼각형의 세 변을 입력합니다.
  • 공식 (a+b+c)/2를 사용하여 삼각형의 반둘레 s를 계산합니다.
  • 헤론의 공식을 사용하여 삼각형의 면적 area = sqrt(s*(s-a)*(s-b)*(s-c))를 계산합니다.
  • 마지막으로 printf 함수를 사용하여 삼각형의 면적을 출력합니다.

main.c 파일에 코드 작성하기

이제 ~/project/ 디렉토리에 새로운 파일 main.c를 생성하고 이전 단계의 코드를 복사합니다.

코드 실행하기

코드를 실행하려면 터미널을 열고 ~/project/ 디렉토리로 이동한 후 다음 명령을 입력하십시오.

gcc main.c -o main
./main

main.c 전체 코드

#include<stdio.h>
#include<math.h>

int main()
{
    // Step 1: Basic Program using Base and Height
    int h, b;
    float area;
    printf("Enter the height of the Triangle: ");
    scanf("%d", &h);
    printf("Enter the base of the Triangle: ");
    scanf("%d", &b);
    area = (h*b)/(float)2;
    printf("The area of the triangle is: %f\n", area);

    // Step 2: Advanced Program using Heron's Formula
    double a, b, c, area2, s;
    printf("Enter the sides of the triangle:\n");
    scanf("%lf%lf%lf", &a, &b, &c);
    s = (a+b+c)/2;
    area2 = sqrt(s*(s-a)*(s-b)*(s-c));
    printf("The area of the Triangle calculated using Heron's formula is: %lf\n", area2);

    return 0;
}

요약

이 랩에서는 C 프로그램을 사용하여 밑변과 높이 방법과 헤론의 공식 (Heron's formula) 방법을 모두 사용하여 삼각형의 면적을 구하는 방법을 배웠습니다. 또한 main.c 파일에서 코드를 작성하고 터미널에서 프로그램을 컴파일하고 실행하는 방법도 배웠습니다.