题目:利用递归方法求5!。
程序分析:递归公式:fn=fn_1*4!
程序设计:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
import java.util.Scanner; public class Ex22 { public static void main(String[] args) { Scanner s = new Scanner(System.in); int n = s.nextInt(); Ex22 tfr = new Ex22(); System.out.println(tfr.recursion(n)); } public long recursion( int n) { long value = 0 ; if (n == 1 || n == 0 ) { value = 1 ; } else if (n > 1 ) { value = n * recursion(n- 1 ); } return value; } } |
方法二利用递归方法求5!。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
public class lianxi22 { public static void main(String[] args) { int n = 5 ; rec fr = new rec(); System.out.println(n+ "! = " +fr.rec(n)); } } class rec{ public long rec( int n) { long value = 0 ; if (n == 1 ) { value = 1 ; } else { value = n * rec(n- 1 ); } return value; } } |