Java 找到no的阶乘。它工作得很好,但我不明白为什么它给我56、89、77和其他一些数字的阶乘0

Java 找到no的阶乘。它工作得很好,但我不明白为什么它给我56、89、77和其他一些数字的阶乘0,java,factorial,Java,Factorial,这是我的阶乘程序代码。它工作得很好,但我不明白为什么它给我56,89,77和其他一些数字的阶乘0 private static void factorial() { int resultant = 1, i; System.out.println("Please Enter any number to find factorial : "); Scanner scan = new Scanner(System.in); int fact = scan.nextIn

这是我的阶乘程序代码。它工作得很好,但我不明白为什么它给我56,89,77和其他一些数字的阶乘0

private static void factorial() {
    int resultant = 1, i;
    System.out.println("Please Enter any number to find factorial : ");
    Scanner scan = new Scanner(System.in);
    int fact = scan.nextInt();
    for (i = 1; i <= fact; i++) {
        resultant = resultant * i;
    }
    System.out.println("Factorial of number : " + resultant);
}
私有静态void factorial(){
int结式=1,i;
System.out.println(“请输入任何数字以查找阶乘:”);
扫描仪扫描=新扫描仪(System.in);
int fact=scan.nextInt();

对于(i=1;i作为乘积一部分的每个偶数都会为阶乘贡献一个尾随零。实际上更精确地说,尾随零计数是a(无限制精度)乘积是输入的尾随零计数之和。在有限精度中,尾随零的数量明显受到数字大小的限制

最后,这种情况很快就发生了,尾随零的数量变得大于或等于32,在这种情况下,
int
的所有位都将为零。同样的情况当然也会发生在
long
,稍晚一点,64个尾随零。在这之前的一段时间,即使结果还不是完全为零,它可能已经停止匹配结果的无限精度

例如,十六进制中的34是

de1bc4d19efcac82445da75b00000000

如果使用32位整数计算,则8个最低有效位将为零。

您应该知道
int
的大小固定为32位。当您的计算结果产生无法放入32位的大数字时,一些位将溢出,产生w您可以尝试使用此代码

private static void factorial() {
    int resultant = 1, i;
    System.out.println("Please Enter any number to find factorial : ");
    Scanner scan = new Scanner(System.in);
    int fact = scan.nextInt();
    for (i = 1; i <= fact; i++) {
        int test=resultant;
        resultant = resultant * i;
        if(resultant<test){
            system.out.println("Looks like overflow occured");
        }   
    }
    System.out.println("Factorial of number : " + resultant);
}
私有静态void factorial(){
int结式=1,i;
System.out.println(“请输入任何数字以查找阶乘:”);
扫描仪扫描=新扫描仪(System.in);
int fact=scan.nextInt();

对于(i=1;i如此大的数字的阶乘将非常大。您必须使用能够存储非常大的数字的数据类型(我们谈论的是数十亿和万亿).BigInteger数据类型可能有效。请尝试一下。

您遇到了整数溢出。如果将
resultant=resultant*i
替换为
resultant=Math.multiplyExact(resultant,i)
您甚至会得到一个
java.lang.arithmetricException:integer overflow
。请改用
BigInteger
。非常感谢您的提醒。我在运行旧程序时忘记了它。