简体   繁体   English

为什么我的阶乘 function 总是返回 1?

[英]Why does my factorial function always return 1?

I'm learning C and came up with this one-line factorial function using a ternary operator on the return, but it always returns 1.我正在学习 C 并想出了这个单行阶乘 function 在返回时使用三元运算符,但它总是返回 1。

#include <stdio.h>

int factorial(int n){
    return  (n > 1) ? factorial(n -1) : 1;
}

int main() {
    for(int i = 0; i < 10; i++){
        printf("%d factorial is %d\n",i,factorial(i));
    }
    return 0;
}

You can see the code returns 1 for values 0 through 9 in this link: https://code.sololearn.com/c7uSnfxw92sl/#c您可以在此链接中看到值 0 到 9 的代码返回 1: https://code.sololearn.com/c7uSnfxw92sl/#c

You forgot to multiply by n你忘了乘以n

int factorial(int n){
    return (n > 1) ? n * factorial(n -1) : 1;
}

That is very easy since we can use the substitution rules.这很容易,因为我们可以使用替换规则。 Eg.例如。

factorial(10);                    // ==
(10 > 1) ? factorial(10 - 1) : 1  // ==
(9 > 1) ? factorial(9 - 1) : 1    // ==
(8 > 1) ? factorial(8 - 1) : 1    // ==
(7 > 1) ? factorial(7 - 1) : 1    // ==
(6 > 1) ? factorial(6 - 1) : 1    // ==
(5 > 1) ? factorial(5 - 1) : 1    // ==
(4 > 1) ? factorial(4 - 1) : 1    // ==
(3 > 1) ? factorial(3 - 1) : 1    // ==
(2 > 1) ? factorial(2 - 1) : 1    // ==
(1 > 1) ? factorial(1 - 1) : 1    // ==
1

Your function is broken.你的 function 坏了。 It does not multiply n with the result of factorial(n - 1).它不会将 n 与阶乘 (n - 1) 的结果相乘。 You could also do it with an accumulator for it to become tail recursion, but you cannot just replace it with factorial(n - 1) since it will not compute the same as factorial(n) .您也可以使用累加器来使其成为尾递归,但您不能只用factorial(n - 1)替换它,因为它的计算方式与factorial(n)不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM