java recursion:当n> 12时,int中的factorial会出错

时间:2015-10-04 21:07:42

标签: java recursion factorial

import java.util.Scanner;



public class factorial {
    public static void main(String [] args){
        Scanner in = new Scanner(System.in);
        int x = 0, y;
        System.out.println("enter factorial number");
        if(in.hasNextInt()){
            x = in.nextInt();// check if the scanner's next token is an int
        }//end if
        y = factorial(x);
        System.out.println("factorials is "+y);
    }//end main

    private static int factorial(int n) {
        // TODO Auto-generated method stub
        if(n==0||n==1){
            return 1;
        }
        else 
        return n*factorial(n-1);//recursive call
    }//end factorial


}//end class

1 个答案:

答案 0 :(得分:5)

这是因为13!大于最大的32位整数。在java中,int总是32位。