其他分享
首页 > 其他分享> > 18、递归

18、递归

作者:互联网

递归

image-20210624154350551

public class MethodDemo09 {
    //2! 2*1
    //3! 3*2*1
    //5! 5*4*3*2*1
    public static void main(String[] args) {
        MethodDemo09 demo09 = new MethodDemo09();
        int result = demo09.recursion(5);
        System.out.println(result);
    }

    public int recursion(int n) {
        if ( n == 1 ) {
            return 1;
        } else {
            return n * recursion(n-1);
        }
    }
}

image-20210624160529501

用for循环求阶乘

public class MethodDemo10 {
    public static void main(String[] args) {
        MethodDemo10 demo10 = new MethodDemo10();
        demo10.recursion();
    }

    //用for循环求阶乘
    public void recursion() {
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入一个整数:");
        int num = sc.nextInt();
        if ( num == 1 ) {
            System.out.println(num + "的阶乘为:1");
            return;
        }
        int result = 1;
        for ( int i = 2; i <= num; i++ ) {
            result = result * i;
        }
        System.out.println(num + "的阶乘为:" + result);
    }
}

当输入的数为 1 时:

image-20210624163753857

当输入的数为 2 时:

image-20210624163821471

标签:递归,int,18,System,num,recursion,阶乘,public
来源: https://www.cnblogs.com/duoruic/p/14934835.html