为什么此阶乘函数不返回?

时间:2019-07-16 04:59:06

标签: javascript recursion

我创建了这个递归函数,用于计算数字的阶乘。第一个参数n是您要为其计算阶乘的数字,第二个参数结果用于在调用函数self时将阶乘计算的状态传递给函数。我的问题是该函数将在函数结束时console.log记录正确的阶乘,但不会返回它。它只会返回数字小于2的阶乘,所有其他返回未定义。我的条件是“ n> = 2”,因此使我认为与此相关,但是我找不到该问题与问题之间的任何关系。为什么此函数未返回正确的阶乘?

function factorial(n, result){

    //checks if result is undefined if so uses n calculate value of result
    //if result isnt undefined it changes its value using "n * ( n - 1)"

    result = result * (n - 1) || n * (n - 1);



   //decreases n, n gets gradually smaller
    n-=1;


 //if n is more the 2 run function again
 //I'm fairly certain this conditional is the root of the issue but personally cant find the relation
    if(n >= 2){
        //passes current state of n and result
        factorial(n,result);
       }
    else {
       //result has the correct value as its printing to the console 
       //correctly, e.g !4 = 4*3*2*1, which equals 24, this prints 24 if you 
       //pass 4 to n.
       console.log(result);
       //if n is smaller then 2 return factorial
       //but it wont return result
        return result;
        };
}

1 个答案:

答案 0 :(得分:1)

您的函数未返回结果的原因是因为您不在factorial(n, result)时返回n >=2的结果

function factorial(n, result){

    //checks if result is undefined if so uses n calculate value of result
    //if result isnt undefined it changes its value using "n * ( n - 1)"

    result = result * (n - 1) || n * (n - 1);



   //decreases n, n gets gradually smaller
    n-=1;


 //if n is more the 2 run function again
 //I'm fairly certain this conditional is the root of the issue but personally cant find the relation
    if(n >= 2){
        //passes current state of n and result
        return factorial(n,result);
       }
    else {
       //result has the correct value as its printing to the console 
       //correctly, e.g !4 = 4*3*2*1, which equals 24, this prints 24 if you 
       //pass 4 to n.
       console.log(result);
       //if n is smaller then 2 return factorial
       //but it wont return result
        return result;
        };
}

然而,编写此代码的最简单方法是重复执行直到达到终止条件

function factorial(n) {
   if(n == 1) {
       return 1;
   }
   return n*factorial(n - 1);
}