递归算法

递归调用是一个方法在其方法体内调用自身的方法调用方式。

使用递归算法往往可以简化代码编写,提高程序的可读性,但是不合适的递归会使程序执行效率变低。

递归调用分为间接递归和直接递归,间接递归用的不多。

编写递归方法是,必须使用if语句强制方法在未执行递归调用前返回返回,如果不这样做,在调用方法后,它将永远不会返回。

下面求n的阶乘:

public class Yihuo {
public static int sun(int n){
if(n<=1)
return 1;
else
return n*sun(n-1);//递归
}
public static void main(String []args) {
Scanner scan=new Scanner (System.in);
System.out.println("输入n的值");
int n=scan.nextInt();
int m=sun(n);
System.out.println("n的阶乘为"+m);
}
}

原文地址:https://www.cnblogs.com/mianyang0902/p/10659448.html