【问题标题】:Why isn't this factorial function returning?为什么这个阶乘函数不返回?
【发布时间】:2019-07-16 04:59:06
【问题描述】:

我创建了这个递归函数来计算一个数字的阶乘。第一个参数 n 是您要为其计算阶乘的数字,第二个参数 result 用于在调用自身时将阶乘计算的状态传递给函数。我遇到的问题是该函数将在函数结束时控制台记录正确的阶乘结果,但不会返回它。它只会返回小于 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;
        };
}

【问题讨论】:

  • 您的if 分支中没有return 语句,因此它返回undefined
  • 改变阶乘(n,result);到“返回阶乘(n,结果);”阶乘函数只会在 n2 时它只调用函数并且不返回任何内容
  • 好的,谢谢 melpomene 和 yash Thakor

标签: javascript recursion


【解决方案1】:

你的函数没有返回结果的原因是你在n >=2时没有返回factorial(n, result)的结果

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);
}

【讨论】:

  • 您只是想使用递归对数字进行阶乘?
  • 您的“简单”解决方案比 OP 的尾递归尝试差得多。 (n, acc = 1) => n <= 1 ? acc : factorial(n-1, n * acc) 更好,并且在 ES2016 实现中永远不会堆栈溢出。
  • @Sylwester:请注意,虽然它在规范中,但 TCO 并没有真正落在大多数 JS 引擎中。
  • @ScottSauyet 仅限 Safari。所有其他引擎都缺少 ES2015/ES6 和 ES2016 功能,所以基本上它们是带有一些新插件的 ES5 引擎。
猜你喜欢
  • 2015-04-21
  • 1970-01-01
  • 2019-05-21
  • 2020-02-22
  • 2015-12-21
  • 1970-01-01
  • 2016-03-21
  • 2018-01-28
  • 1970-01-01
相关资源
最近更新 更多