0416-递归

package demoFile;
/*
递归:指在当前方法内调用自己的这种现象。递归分为直接递归和间接递归。
注意:
    1.递归一定要有条件限定,保证递归能够停止下来,否则会发生栈内存溢出。
    2.在递归中虽然有限定条件,但是递归次数不能太多,否则也会发生栈内存溢出。
    3.构造方法,禁止递归。
 */
public class Demo02Sum {
    public static void main(String[] args) {
        System.out.println("5的累计和"+sum(5));
        System.out.println("5的阶乘:"+chen(5));
    }

    //递归方法计算累积求和
    public static int sum(int n) {
        if (n == 1) {
            return 1;
        }
        return sum(n - 1) + n;
    }
    //递归方法计算阶乘
    public static int chen(int n) {
        if (n == 1) {
            return 1;
        }
        return chen(n - 1) * n;
    }
}

猜你喜欢

转载自www.cnblogs.com/sdlz/p/12721351.html