我要做的就是打印阶乘 数字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();
}
答案 0 :(得分:1)
您在循环内递减n
,因此它始终会在0
和1
之间翻转。此外,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));
}