본문 바로가기
C and C++/C and C++ Examples

[C Examples] Recursive power function: 제곱근 계산기

by Henry Cho 2023. 10. 30.
728x90

Recursive power function: 제곱근 계산기

포스트 난이도: HOO_Intern


# subTitle

이번 포스트에서는 반복문을 사용하지 않고 Recursive를 활용해서 제곱근을 계산해 주는 power function에 대한 예제를 살펴볼 수 있다. 아래의 예제코드를 보면 float type의 power라는 사용자 정의 함수가 작성이 되어 있는 걸 알 수 있다. 해당 블록을 살펴보면 if statement를 사용하여 반복할 조건과 아닐 조건을 설정해 줄 수 있다. 아래의 코드에서는 exponent가 0으로 더 이상 없을 경우 끝이 나고 else문에서는 exponent가 1씩 줄어들면서 base 값에 곱해지는 반복적인 recrusive case를 살펴볼 수 있다. 이처럼 자주 사용하는 기능을 사용자 지정 함수로 작성해 줘서 쉽게 기능을 활용할 수 있다. 이번 예제코드를 통해서 함수를 설정하는 방법과 Recursvie가 어떻게 적용되고 있는지에 대해서 알 수 있다.


#include <stdio.h>

float power(float base, float exponent) {
    // Base case
    if (exponent == 0) {
        return 1;
    }
    // Recursive case
    else {
        return base * power(base, exponent - 1);
    }
}

int main() {
    float base;
    float exponent;

    printf("Recursive Power Function\n");
    printf("Enter base: ");
    scanf("%f", &base);
    printf("Enter exponent: ");
    scanf("%f", &exponent);

    float result = power(base, exponent);

    printf("Result: %.2f\n", result);
    return 0;
}

Figure 1. Result of example code


# github link

https://github.com/WhoisHOO/HOOAI/blob/main/C%20Examples/recursive_power_function


 

728x90

댓글