long rfact(int n)
{
long ans;
if (n > 0)
ans = n * rfact(n - 1);
else
ans = 1;
return ans;
}
当 n = 1 的时候 ans = 1* ans(0) ;
ans(0) 的执行结果就是返回一个 ans = 1;
所以表达式ans = 1* ans(0) 的结果为ans = 1 * 1 = 1;
最终n = 1时返回的结果是 ans = 1;
n=1的时候不会执行 ans = n * rfact(n - 1);而是直接返回1 (ans = 1;)
n=1时。代码执行到rfact(n-1)时,实际上是调用了rfact(0),这个时候,执行函数的话,会触发if的判断条件,使其返回ans=1
没有啊n=1的时候,也会返回1,你传进去1,1>0,执行ans = n * refact(n-1),递归推进,传0进去,0>0为false,返回ans=1,递归返回,1*1结果为1啊
n=1 ans=n* rfact(n-1) ,也是ans=0 但计算机会判断 结果返回asn=1
if (n > 0),,,,这个判断就是说,,,,大于0才阶乘,,,不大于零,,,就返回1
解决方案,如果n==1就结束循环,不等于1才递归。
public class jiecheng {
public static int fun(int num1){
if(num1==1)
return 1;
else return num1*fun(num1-1); }
public static void main(String[] args){
int num=5;
int jiec=1;
jiec = fun (num);
System.out.println(jiec); }
}
递归的条件那里设置n>1,=1时就不需要继续递归调用了,执行是没问题的,多了一层调用