我正在尝试使用这个简单的代码来计算5的阶乘。但是我得到了"未定义"作为结果。我知道其他方法,但这有什么问题?
<!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>
答案 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
}
}
顺便说一句,你的方法可能有效,但风格很糟糕。可以这样做:
function calfact(num){
if(num!=1){
return calfact(num-1)*num;
}else{
return 1;
}
}
或简短:
calfact=num=>num==1?1:calfact(num-1)*num;
答案 1 :(得分: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;
}
}
你的函数正在使用一个全局变量,这不是一个好主意,因为它意味着功能不是自包含的;并且不是真正的阶乘函数,因为您实际上使用了两个输入(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);
}