2017-04-15 49 views
0

我正在尝试这个简单的代码来计算5阶乘因子。但是我得到“undefined”作为结果。我知道其他方法,但是这有什么问题?javascript factorial递归

<!doctype html> 
<html> 
<head> 
<meta charset="utf-8"> 
<title> Learning </title> 
<head> 
<body> 
<h2> Welcome<h2> 
<p id="demo"></p> 
<script> 
var fact=5; 
function calfact(num) 
{ 
if(num!=1) 
    { 
    fact=fact*(num-1); 
    num=num-1; 
    calfact(num); 
    } 
else 
    { 
    return fact; 
    } 
} 

document.getElementById("demo").innerHTML=calfact(5); 
</script> 
</body> 
</html>   
+2

if(num!= 1)该函数什么也没有返回(undefined) –

回答

0

如果你想从一个递归函数的结果,通过函数的所有代码路径必须返回的东西。您的代码在num!=1的情况下不会返回任何内容。它应该返回自己调用的结果,例如(见***线):

var fact=5; 
function calfact(num) 
{ 
if(num!=1) 
    { 
    fact=fact*(num-1); 
    num=num-1; 
    return calfact(num); // *** 
    } 
else 
    { 
    return fact; 
    } 
} 

你的功能,因为它意味着funtion不自足使用全局变量,它是不是一个好主意;而不是真正的阶乘函数,因为你有效地利用两个输入(fact   —全球 和num,参数)

如果你想有一个真正的阶乘,你并不需要一个全局变量,

function factorial(num) { 
 
    if (num < 0) { 
 
     throw new Error("num must not be negative"); 
 
    } 
 
    if (num <= 1) { 
 
     // Both 1! and 0! are defined as 1 
 
     return 1; 
 
    } 
 
    return num * factorial(num - 1); 
 
} 
 
console.log(factorial(5)); // 120

当然,或者更简洁:

从参数本身只是工作
function factorial(num) { 
    if (num < 0) { 
     throw new Error("num must not be negative"); 
    } 
    return num <= 1 ? 1 : num * factorial(num - 1); 
} 

(更多关于0!:https://en.wikipedia.org/wiki/Factorial

+0

通过“代码路径”,你指的是所有的块? 谢谢,顺便说一句!它解决了这个问题。 –

+0

@ShivamMishra:“代码路径”是执行可以通过函数移动的方式(如跟随步行路径)。例如,当'num'为'1'时,我们在函数中使用一个路径(使用原始函数中的'else'块)。当num不是1时,我们在函数中走一条不同的路径。 –

+0

明白了。我预计代码将遵循我的直觉。另外,感谢提及不使用全局变量。 –

1
var fact=5; 
function calfact(num){ 
    if(num!=1){ 
     fact=fact*(num-1); 
     num=num-1; 
     return calfact(num);//the missing thing 
    }else{ 
     return fact;//why fact? i think it should be 1 
    } 
} 

顺便说一句,你的方法也许是工作,但真的不好style.May做到这一点:

function calfact(num){ 
    if(num!=1){ 
    return calfact(num-1)*num; 
    }else{ 
    return 1; 
} 
} 

或短:

calfact=num=>num==1?1:calfact(num-1)*num;