递归调用求一个整型数的阶乘
package factresurion;
public class Fact {
/**
* 对某一个整型数,求阶乘
* @param n 某一个整型数
* @return int 该数的阶乘
*/
public int getFact(int n){
//声明返回变量
int rtn=1;
//判断
if(n==0){
rtn=1;
}else{
rtn=n*this.getFact(n-1);
}
//返回
return rtn;
}
}在这里插入代码片
package factresurion;
public class TestFact {
public static void main(String[] args) {
Fact f=new Fact();
System.out.println(f.getFact(6));
}
}
**例如求5的阶乘
s=6!
计算是:s=65432*1
程序的执行过程为:
rtn=nthis.getFact(n-1)
rtn=6this.getFact(5);
5this.getFact(4)
4this.getFact(3)
3this.getFact(2)
2this.getFact(1)
**
一个方法体内调用它自身,被称为方法递归。方法递归包含了一种隐式的循环,它会重复执行某段代码,但这种重复执行无须循环控制