0
Follow
0
View

C language function cyclic and recursive basic problems

skz385489 注册会员
2023-02-25 10:08

the reference answer GPT ᴼ ᴾ ᴱ ᴺ ᴬ ᴵ < br / > your recursive function dg, under the condition of no set n = 0 end have been proceed cause recursion, a compiler error.
can change the recursive function to:

int dg(int n)
{
    if (n == 0) {
        return 1;
    } else {
        return n * dg(n-1);
    }
}

This completes the recursion when n=0 and returns 1 as the termination condition.

Also, your xh code is correct, but if you enter a large number in the main function, such as 20, the program may output the wrong result, because int can only represent up to 2^31-1, beyond which overflow occurs. If you need to calculate the factorial of a larger number, consider using a high precision number library.

dgangd 注册会员
2023-02-25 10:08

dg function n=0 returns 1, missing this

About the Author

Question Info

Publish Time
2023-02-25 10:08
Update Time
2023-02-25 10:08