简体   繁体   English

为什么我的阶乘函数返回NaN?

[英]Why is my factorial function returning NaN?

I wrote a factorial function using recursion and a while-loop but it's return value is NaN whenever it is called. 我使用递归和while循环编写了阶乘函数,但每次调用它的返回值都是NaN。 Please I want to know why? 请问我想知道为什么吗? and how to fix it? 以及如何解决?

Function 功能

function factorial(n) {
    while(n > 0)
        return factorial(n - 1) * n;
}

You're missing the return statement for the base case. 您缺少基本情况的return语句。 The function returns undefined when you return without a value, and when you multiply that you get NaN . 当您返回不带值的值时,该函数将返回undefined的值;当乘以该值时,该函数将返回NaN

Also, you're not looping, so you should use if rather than while . 另外,您不会循环播放,因此应使用if而不是while

 function factorial(n) { if (n > 0) { return factorial(n - 1) * n; } else { return 1; } } console.log(factorial(10)); 

You can also write it with looping instead of recursion. 您也可以使用循环而不是递归来编写它。

 function factorial(n) { result = 1; for (var i = 1; i <= n; i++) { result *= i; } return result; } console.log(factorial(10)); 

If you track your recursion, you'll see when n reaches 1, which make n-1 = 0 and the factorial(0) is called, your function does not know what to do next and does not return any number (NaN). 如果您跟踪递归,则会看到n达到1时(使n-1 = 0并调用了factorial(0)),您的函数不知道下一步该怎么做,并且不返回任何数字(NaN)。 That NaN multiplies with all other things returning another NaN. NaN与所有其他事物相乘,返回另一个NaN。

Add an instruction for your function in to handle n = 0: 为您的函数添加一条指令以处理n = 0:

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

Just add the base case n === 0 to n === 1 to end the tail recursion. 只需将n === 0的基本情况添加到n === 1即可结束尾递归。

 console.log(function factorial(n) { if (n === 0 || n === 1) { return 1; } return factorial(n - 1) * n; }(4)); 

您也可以将其写成一行:

const factorial = (n) => (n > 1) ? factorial(n-1) * n : 1

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

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