黃柏諺java遞迴函數Recursion=Recursive Function=Recursive Methods
public class Main { /*黃柏諺recursion遞迴函數*/
public static void main(String[] args) {
int x = 11; /*Java程式必須以main開始*/
for (int i = 0; i < x; i++)/*for迴圈*/
{ System.out.print(i + "累加等於" + sum(i));
System.out.println("累乘等於" + f(i));}}
public static int sum(int k) {
if (k > 0) { return k + sum(k - 1);}
else {return 0;} } /*函數sum呼叫自己,稱遞迴*/
public static int f(int k) {
if (k > 0) { return k * f(k - 1);}
else {return 1;} } /* 0!=1, 7!=7*6!,......*/
}
留言
張貼留言