Java打印因子1-30

时间:2017-03-25 15:28:48

标签: java factorial

我要做的就是打印阶乘 数字0-30。当我运行它时,它无休止地打印Factorial = 0。有人能告诉我如何纠正这个问题吗?

public static void factor(){

    int n=0;
    int factorial = 1;
    while (n<=0&n<=30)
    {
        n=n++;
      factorial = factorial * n;
      n--;
      System.out.println("Factorial = " + factorial);
    }


}


public static void main(String[] args) {
   factor();
}

1 个答案:

答案 0 :(得分:1)

您在循环内递减n,因此它始终会在01之间翻转。此外,int无法容纳如此大的数字,long也不能。你必须使用更聪明的东西,比如BigInteger

int n = 0;
BigInteger factorial = BigInteger.ONE;
while (n <= 30) {
    System.out.printf("Factorial(%d) = %s%n", n, factorial);
    n++;
    factorial = factorial.multiply(BigInteger.valueOf(n));
}