Created
May 14, 2012 15:25
-
-
Save faryne/2694565 to your computer and use it in GitHub Desktop.
利用遞迴函數處理階乘的問題
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.io.*; | |
import java.util.Scanner; | |
class test { | |
/** | |
* @param args | |
*/ | |
public static void main(String[] args) throws java.lang.Exception { | |
// TODO Auto-generated method stub | |
try { | |
System.out.print("Enter a number: "); | |
Scanner scanner = new Scanner(System.in); // 取得使用者的輸入 | |
String target = scanner.next(); // 轉換成String類型資料 | |
int a = Integer.parseInt(target); // 再轉換成數值型態資料 | |
int b = fic(a); // 執行遞迴函數 | |
System.out.println(b); // 印出執行結果 | |
} catch (Exception e) { | |
System.out.println(e.getMessage()); | |
} | |
} | |
// 遞迴函數 | |
public static int fic (int n) { | |
if (n <= 1) | |
return 1; | |
else | |
return n * fic(n - 1); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment