s-day08--递归求阶乘的代码
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
package com.inmind.dg02;
|
||||||
|
/*
|
||||||
|
10.递归求阶乘的代码
|
||||||
|
5! = 5*4*3*2*1
|
||||||
|
4! = 4*3*2*1
|
||||||
|
3! = 3*2*1
|
||||||
|
2! = 2*1
|
||||||
|
1! =1
|
||||||
|
|
||||||
|
阶乘另一种计算方式:
|
||||||
|
5! = 5*4!
|
||||||
|
4! = 4*3!
|
||||||
|
3! = 3*2!
|
||||||
|
2! = 2*1!
|
||||||
|
1! =1
|
||||||
|
|
||||||
|
求阶乘的数学规律是 n! = n*(n-1)!
|
||||||
|
|
||||||
|
核心思想:递归代码如何编写??
|
||||||
|
1.判断当前是否是结束条件,如果是就结束(return)
|
||||||
|
2.如果不是结束条件,那么按数学规律或者逻辑规律调用自己
|
||||||
|
|
||||||
|
*/
|
||||||
|
public class Demo09 {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
int jc = getJC(10);
|
||||||
|
System.out.println(jc);
|
||||||
|
|
||||||
|
}
|
||||||
|
|
||||||
|
//定义一个求阶乘的方法
|
||||||
|
public static int getJC(int n) {
|
||||||
|
//判断结束条件
|
||||||
|
if (n == 1) {
|
||||||
|
return 1;//结束递归,返回1
|
||||||
|
}
|
||||||
|
return n*getJC(n-1);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user