402 尾端遞迴階乘計算

import java.util.Scanner;
public class JPA402 {
    static Scanner keyboard = new Scanner(System.in);
    public static void main(String args[]) {
        int n;
        System.out.print("Input n (0 <= n <= 16) :");
        n=keyboard.nextInt();
        while(n!=999){
        System.out.println(n+"的階乘(尾端遞迴) = "+forloop(n,1));
        System.out.println(n+"的階乘(迴圈) = "+fun(n,1));
        System.out.print("Input n (0 <= n <= 16) :");
        n=keyboard.nextInt();
        }
    }
static int fun(int x,int y){
if(x>0){
return fun(x-1,x*y);
}
else{
return y;
}
}
static int forloop(int x,int y){

while(x>0){
y=y*x;
x--;
}
return y;
}
}

沒有留言:

張貼留言