s-day08-递归求阶乘的代码
This commit is contained in:
@@ -0,0 +1,44 @@
|
||||
package com.inmind.digui02;
|
||||
/*
|
||||
递归求阶乘的代码
|
||||
递归代码:
|
||||
1.自己调用自己
|
||||
2.递归代码必须要有结束条件
|
||||
|
||||
阶乘:
|
||||
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)!
|
||||
|
||||
总结:如何编写递归方法,先找到规律,要有调用自己的规律,必定要有结束条件
|
||||
|
||||
需求:传入一个整数n值,求n的阶乘
|
||||
比如: 3! = 1*2*3
|
||||
*/
|
||||
public class Demo09 {
|
||||
public static void main(String[] args) {
|
||||
int result = getJC(3);
|
||||
System.out.println(result);
|
||||
}
|
||||
|
||||
//递归求阶乘方法,求n的阶乘
|
||||
public static int getJC(int n) {
|
||||
//递归结束条件
|
||||
if (n == 1) {
|
||||
return 1;
|
||||
}
|
||||
//数学规律是n! = n*(n-1)!
|
||||
return n*getJC(n-1);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user