C언어 팩토리얼 재귀함수 구현 시 return 1의 의미가 뭔가요?

Asked 1 years ago, Updated 1 years ago, 71 views

#define _CRT_SECURE_NO_WARNIGS
#include<stdio.h>
#include<stdlib.h>

int factorial(int n);

int main() {
    int n;
    scanf("%d", &n);
    printf("%d\n", factorial(n));
    return 0;
}

int factorial(int n) {
    if (n > 0)
        return (n * factorial(n - 1));
    else
        return 1;
}

I don't know what return 1 means in the factorial function. If you enter 5, you get 0 if you write return 0, you get 120 (correct answer) if you write return 1, and you get -120 if you put return -1. I wonder what each return value means.

c function recursion factorial return-value

2022-09-22 17:54

1 Answers

Factory F_n has the same ignition expression as the recursive function.

The factory can be defined by the following two conditions by the ignition formula:

If you make these two conditions a function, the upper condition corresponds to the (n>0) branch, and the else side corresponds to the lower branch.

When you get a recursive function, think of the ignition equation you learned in high school.


2022-09-22 17:54

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.