使用方法递归

使用方法递归

public class Demo05 {
    public static void main(String[] args) 
    {
        int f = f2(5);
        System.out.println(f);
    }
    //不使用递归的阶乘方法
    public static int f(int n)
    {
        int sum = n;
        while(n!=1)
        {
            n -= 1;
            sum *= n;
        }
        return sum;
    }
    //使用递归的阶乘方法
    public static int f2(int n)
    {
        if(n==1)
        {
            return 1;
        }
        else
        {
        return n*f(n-1);
        }
    }
}

posted @ 2023-06-04 21:45  晚枫zz  阅读(7)  评论(0)    收藏  举报