What is wrong with this recursion function? fac(5) gives NaN
function fac(num){
while(num>2){
return(num*fac(num-1))
}
}
fac(1)
returns nothing, which is undefined
, and undefined*1
is NaN
, that's why.
Change your code to
function fac(num){
return num>2 ? num*fac(num-1) : 1;
}
The correct way should be:
function fact(num) {
if(num > 2)
return num * fact(num - 1);
else
return num;
}
NaN - not a number error , occurs usually but not limited to when we try to apply a numerical operation to a value which is not a number.
The Issue at hand is when the input value is less than 2 , the function return undefined
, which is not a number, so the return (num*fac(num-1))
will fail due to num * undefined
. to fix this , we have to return a value when number is 2 or less than 2.
function fact(num) {
if(num > 2)
return num * fact(num - 1);
else
return num;
}
What's wrong with your code
function fac(num){
while(num>2){
return(num*fac(num-1))
}
}
No return value for num <= 2
. So, at some point your code will multiply Number
with undefined
which results in NaN
while
loop is not needed
function fac(num) { return (num > 2) ? num * fac(num - 1) : 1; } alert(fac(5));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.