递归函数

递归函数

    在一定程度上可以为循环

    自己调用自己本身的方法被称为递归函数

    *** 最重要的就是

 

6!

 

public class Test {
    public static void main(String[] args) {
        //方法一(for循环)
        int result=1;
        
        for (int i = 6; i >= 1; i--) {
            result=result*i;
        }
        System.out.println(result);
        
        
        //方法二(递归)
        System.out.println(fac(6));    
    }
    public static int fac(int num) {
        if (num==1) {
            return 1;
        }
        return num*fac(num-1);
    }
    
}

 

 

 斐波那契数列

 

          

public class Demo3 {  
    // 使用递归方法  
    private static int getFibo(int i) {  
        if (i == 1 || i == 2)  
            return 1;  
        else  
            return getFibo(i - 1) + getFibo(i - 2);  
    }  
  
    public static void main(String[] args) {  
        System.out.println("斐波那契数列的前20项为:");  
        for (int j = 1; j <= 20; j++) {  
            System.out.print(getFibo(j) + "\t");  
            if (j % 5 == 0)  
                System.out.println();  
        }  
    }  
}  

 

posted @ 2019-06-26 08:40  Y幽寒  阅读(157)  评论(0编辑  收藏  举报