C 언어로 거듭제곱 계산하기

CBeginner
지금 연습하기

소개

이 실습에서는 C 프로그래밍에서 거듭제곱과 지수를 계산하는 방법을 배웁니다. 이 실습은 주로 사용자로부터 밑과 지수 값을 읽고, 수동 루프 또는 내장 pow() 함수를 사용하여 거듭제곱을 계산하는 두 가지 주요 단계로 구성됩니다. 이 실습을 마치면, 많은 수학 및 과학 응용 분야에서 기본적인 연산인 C 에서 거듭제곱 계산을 수행하는 방법에 대한 확실한 이해를 얻게 될 것입니다.

밑과 지수 읽기

이 단계에서는 C 프로그램에서 거듭제곱을 계산하기 위한 밑과 지수 값을 읽는 방법을 배웁니다. 사용자에게 이 값들을 입력하도록 요청하는 간단한 프로그램을 만들 것입니다.

먼저 ~/project 디렉토리에 새로운 C 파일을 생성합니다.

cd ~/project
nano power_calculation.c

이제 밑과 지수를 읽는 다음 코드를 입력합니다.

#include <stdio.h>

int main() {
    int base, exponent;

    // 사용자에게 밑 입력 요청
    printf("Enter the base number: ");
    scanf("%d", &base);

    // 사용자에게 지수 입력 요청
    printf("Enter the exponent: ");
    scanf("%d", &exponent);

    // 입력된 값 출력
    printf("Base: %d\n", base);
    printf("Exponent: %d\n", exponent);

    return 0;
}

이제 프로그램을 컴파일하고 실행해 봅시다.

gcc power_calculation.c -o power_calculation
./power_calculation

예시 출력:

Enter the base number: 5
Enter the exponent: 3
Base: 5
Exponent: 3

코드 설명:

  • scanf() 함수는 사용자로부터 정수 입력을 읽는 데 사용됩니다.
  • %d는 정수를 위한 형식 지정자입니다.
  • &base&exponent는 입력 값이 저장될 메모리 주소를 전달합니다.
  • 이 프로그램은 단순히 밑과 지수 값을 읽고 표시합니다.

이 단계는 사용자로부터 필요한 입력을 얻음으로써 거듭제곱 계산을 위한 기반을 마련합니다.

루프 또는 pow() 함수 사용

이 단계에서는 C 에서 거듭제곱을 계산하는 두 가지 방법, 즉 수동 루프와 math 라이브러리의 내장 pow() 함수를 사용하는 방법을 배웁니다.

먼저 이전의 power_calculation.c 파일을 수정하여 거듭제곱 계산을 구현해 봅시다.

cd ~/project
nano power_calculation.c

방법 1: 루프 사용

#include <stdio.h>

int calculate_power_loop(int base, int exponent) {
    int result = 1;
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }
    return result;
}

int main() {
    int base, exponent;

    printf("Enter the base number: ");
    scanf("%d", &base);

    printf("Enter the exponent: ");
    scanf("%d", &exponent);

    int power_result = calculate_power_loop(base, exponent);

    printf("%d raised to the power of %d is: %d\n", base, exponent, power_result);

    return 0;
}

방법 2: pow() 함수 사용

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

int main() {
    int base, exponent;

    printf("Enter the base number: ");
    scanf("%d", &base);

    printf("Enter the exponent: ");
    scanf("%d", &exponent);

    // 참고: pow() 는 double 을 반환하므로 int 로 형변환합니다.
    int power_result = (int)pow(base, exponent);

    printf("%d raised to the power of %d is: %d\n", base, exponent, power_result);

    return 0;
}

수학 라이브러리와 함께 프로그램을 컴파일합니다.

gcc power_calculation.c -o power_calculation -lm

예시 출력:

Enter the base number: 2
Enter the exponent: 3
2 raised to the power of 3 is: 8

코드 설명:

  • 루프 방법은 기저를 자기 자신으로 지수만큼 곱합니다.
  • math.hpow() 함수는 내장된 거듭제곱 계산 기능을 제공합니다.
  • 컴파일 시 -lm 플래그를 사용하여 수학 라이브러리를 연결해야 합니다.
  • pow() 결과를 int로 형변환하여 정수 계산과 일치시킵니다.

결과 출력

이 단계에서는 C 에서 결과를 다양한 방식으로 표현하는 방법을 보여주며, 거듭제곱 계산 프로그램을 개선하여 더 자세하고 형식화된 출력을 제공합니다.

power_calculation.c 파일을 수정해 봅시다.

cd ~/project
nano power_calculation.c

다음과 같은 포괄적인 코드를 추가합니다.

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

void print_power_result(int base, int exponent, int result) {
    // 기본 출력 형식
    printf("Basic Result: %d^%d = %d\n", base, exponent, result);

    // 정렬된 형식 출력
    printf("Formatted Result: %2d raised to the power of %2d equals %5d\n",
           base, exponent, result);

    // 큰 수를 위한 과학적 표기법
    printf("Scientific Notation: %d^%d = %.2e\n", base, exponent, pow(base, exponent));
}

int calculate_power_loop(int base, int exponent) {
    int result = 1;
    for (int i = 0; i < exponent; i++) {
        result *= base;
    }
    return result;
}

int main() {
    int base, exponent;

    printf("Enter the base number: ");
    scanf("%d", &base);

    printf("Enter the exponent: ");
    scanf("%d", &exponent);

    int power_result = calculate_power_loop(base, exponent);

    // 결과 출력 함수 호출
    print_power_result(base, exponent, power_result);

    return 0;
}

프로그램을 컴파일합니다.

gcc power_calculation.c -o power_calculation -lm

프로그램을 실행합니다.

./power_calculation

예시 출력:

Enter the base number: 5
Enter the exponent: 3
Basic Result: 5^3 = 125
Formatted Result:  5 raised to the power of  3 equals   125
Scientific Notation: 5^3 = 1.25e+02

코드 설명:

  • print_power_result()는 여러 출력 형식을 보여줍니다.
  • 기본 출력은 간단한 계산을 보여줍니다.
  • 형식화된 출력은 정렬을 위해 너비 지정자를 사용합니다.
  • 과학적 표기법은 큰 수에 유용합니다.
  • %.2e는 2 자리 소수점으로 과학적 표기법으로 숫자를 표시합니다.

요약

이 실험에서는 사용자로부터 밑과 지수 값을 읽어들인 다음, 두 가지 다른 방법 (수동 루프와 내장 pow() 함수) 을 사용하여 거듭제곱을 계산하는 방법을 배웠습니다. 루프 기반 거듭제곱 계산 함수와 pow() 함수 호출을 구현하고, 그 결과를 비교했습니다. 이를 통해 C 프로그래밍에서 거듭제곱과 지수를 계산하는 다양한 접근 방식을 이해할 수 있었습니다.