我试图找到t数的阶乘,并且每个数字n的输入都由用户提供。

1 < t <= 100
1 < n <= 100


我的代码是:

import java.util.Scanner;
import java.math.BigInteger;

public class fact {
    public static void main(String args[]) {
        int t = 0, i = 0;
         BigInteger result = BigInteger.valueOf(1);
         BigInteger x1 = BigInteger.ONE;
         Scanner sc = new Scanner(System.in);
         t = sc.nextInt();
         BigInteger a[] = new BigInteger[t];

        for(i = 0; i < t; i++) {
           a[i] = BigInteger.valueOf(sc.nextInt());
        }

        for(i = 0; i < t; i++) {
            while(!a[i].equals(x1)) {
               result = result.multiply(a[i]);
               a[i].subtract(BigInteger.valueOf(1));
            }
            System.out.println(result);
            result = x1;
        }
    }
}


对于上面的代码,我没有收到任何错误,它可以正常编译,当我执行它时,它只会不断获取输入,而不会输出任何输出。

最佳答案

在这行上:

a[i].subtract(BigInteger.valueOf(1));


由于BigInteger是不可变的,因此subtract()返回新的BigInteger。您需要存储结果,否则将陷入无尽的循环。改成

a[i] = a[i].subtract(BigInteger.ONE);

07-24 09:37
查看更多