/**
* 递归规则:
* - 执行一个方法时,就创建一个新的受保护的独立空间(栈空间)
* - 方法的局部变量是独立的,不会相互影响, 比如n变量如果方法中使用的是引用类型变量(比如数组),就会共享该引用类型的数据.
* - 递归必须向退出递归的条件逼近,否则就是无限递归,出现StackOverflowError)
* - 当一个方法执行完毕,或者遇到return,就会返回,遵守谁调用,就将结果返回给谁,同时当方法执行完毕或者返回时,该方法也就执行完毕。
*/
public class Factorial {
//阶乘
public static int factorial(int n) {
if (n == 1) {
return 1;
} else {
return factorial(n - 1) * n;
}
}
//递归打印
public static void test(int n) {
if (n > 2) {
test(n - 1);
}
System.out.println("n=" + n);
}
public static void main(String[] args) {
test(4);
//n=2
//n=3
//n=4
System.out.println("factorial(2) = " + factorial(2));
}
}
09.递归
猜你喜欢
转载自www.cnblogs.com/fly-book/p/11648642.html
今日推荐
周排行