摘要:[JAVA] 100! 階乘使用遞迴Method
利用遞迴完成階乘(100!),輸出在螢幕上。
JAVA:
01
import java.io.*;
02
import java.text.*;
03
04
public class test{
05
public static void main(String args[]) throws Exception
06
{ //程式進入點
07
String getbr;
08
BufferedReader br= new BufferedReader(new InputStreamReader(System.in));
09
int x=0;
10
/*****請使用者輸入選項**********/
11
12
while (x>=0)
13
{
14
System.out.print("請輸入要計算階乘的數字:");
15
getbr = br.readLine();
16
x=Integer.parseInt(getbr);
17
if (x<0)
18
{
19
System.out.println("謝謝!再見!");
20
continue;
21
}
22
//引用類別
23
DecimalFormat numberFormat = new DecimalFormat("#");
24
String s;
25
System.out.println(x+ "!="+ rfc(x));
26
System.out.print(x+ "!="+ String.format("%.2e\n",rfc(x)));//科學記號
27
System.out.println(x+ "!="+ numberFormat.format(rfc(x)));
28
} //while結束
29
} //main 結束
30
private static double rfc(int g)
31
{
32
switch (g)
33
{
34
case 1:
35
return 1;
36
//break;
37
default:
38
return g * rfc(g - 1);
39
}
40
}
41
}
42

02

03

04

05

06

07

08

09

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42
輸出結果:
100!=9.33e+157
100!=93326215443944100000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000
執行結果畫面:
http://java.sun.com/j2se/1.4.2/docs/api/java/text/DecimalFormat.html
http://java.sun.com/j2se/1.4.2/docs/api/java/text/NumberFormat.html
範例下載:test.rar
小曼加油!!!
若有謬誤,煩請告知,新手發帖請多包涵
Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET