【JAVA小白】问关于阶乘计算,算出来等于0的问题

代码如下:

import java.util.Scanner;

public class Factorial {
    public static void main(String[] args) {
        System.out.println("---开始---");
        Scanner input = new Scanner(System.in);
        int i ;
        int j;
        int sum = 1;
        System.out.print("请输入要阶乘的数字:");
        i = input.nextInt();
        j = i;
        while (i >= 1) {
            sum *= i;
            i--;
            
        }
        System.out.println(j+"的阶乘为:"+sum);
    }
}

代码测试,输入5,6,7,8 这些都没问题,算出来都是对的
但是输入100,99之类的 得出来结论是0
是咋回事呢?如图

clipboard.png

阅读 3.3k
3 个回答
public class ForProject {
    public static void main(String[] args) {
    int maxnum = 2147483647;
    int maxnum = 2147483648;//超出范围了
    }

}

大兄弟,你需要对基础数据类型进行学习啊。。。int的取值范围。。。

修改下栗子

public class ForProject {
    public static void main(String[] args) {
        System.out.println("---开始---");
        int i =99;

        int sum = 1;
        long temp = 0;

        while (i >= 1) {
            temp = sum;
            sum *= i;
            i--;
            System.out.println(" "+i+" * "+ temp+" = "+sum);

        }

    }

}

结果是

 98 * 1 = 99
 97 * 99 = 9702
 96 * 9702 = 941094
 95 * 941094 = 90345024
 94 * 90345024 = -7157312
 93 * -7157312 = -672787328
 92 * -672787328 = 1855287936
 91 * 1855287936 = -1112201728
 90 * -1112201728 = 1868857856
 89 * 1868857856 = 693482496
 88 * 693482496 = 1590400000
 87 * 1590400000 = -1778720768
 86 * -1778720768 = -129884160
 85 * -129884160 = 1714864128
 84 * 1714864128 = -265437184
 83 * -265437184 = -821886976
 82 * -821886976 = 502857728
 81 * 502857728 = -1715339264
 80 * -1715339264 = -1503526912
 79 * -1503526912 = -23068672
 78 * -23068672 = -1822425088
 77 * -1822425088 = -415236096
 76 * -415236096 = -1908408320
 75 * -1908408320 = 989855744
 74 * 989855744 = 1224736768
 73 * 1224736768 = 436207616
 72 * 436207616 = 1778384896
 71 * 1778384896 = -805306368
 70 * -805306368 = -1342177280
 69 * -1342177280 = 536870912
 68 * 536870912 = -1610612736
 67 * -1610612736 = -2147483648
 66 * -2147483648 = -2147483648
 65 * -2147483648 = 0
 64 * 0 = 0
 63 * 0 = 0
 62 * 0 = 0
 61 * 0 = 0
 60 * 0 = 0
 59 * 0 = 0
 58 * 0 = 0
 57 * 0 = 0
 56 * 0 = 0
 55 * 0 = 0
 54 * 0 = 0
 53 * 0 = 0
 52 * 0 = 0
 51 * 0 = 0
 50 * 0 = 0
 49 * 0 = 0
 48 * 0 = 0
 47 * 0 = 0
 46 * 0 = 0
 45 * 0 = 0
 44 * 0 = 0
 43 * 0 = 0
 42 * 0 = 0
 41 * 0 = 0
 40 * 0 = 0
 39 * 0 = 0
 38 * 0 = 0
 37 * 0 = 0
 36 * 0 = 0
 35 * 0 = 0
 34 * 0 = 0
 33 * 0 = 0
 32 * 0 = 0
 31 * 0 = 0
 30 * 0 = 0
 29 * 0 = 0
 28 * 0 = 0
 27 * 0 = 0
 26 * 0 = 0
 25 * 0 = 0
 24 * 0 = 0
 23 * 0 = 0
 22 * 0 = 0
 21 * 0 = 0
 20 * 0 = 0
 19 * 0 = 0
 18 * 0 = 0
 17 * 0 = 0
 16 * 0 = 0
 15 * 0 = 0
 14 * 0 = 0
 13 * 0 = 0
 12 * 0 = 0
 11 * 0 = 0
 10 * 0 = 0
 9 * 0 = 0
 8 * 0 = 0
 7 * 0 = 0
 6 * 0 = 0
 5 * 0 = 0
 4 * 0 = 0
 3 * 0 = 0
 2 * 0 = 0
 1 * 0 = 0
 0 * 0 = 0

99!已经是天文数字了吧,别说int,估计long都表示不了

推荐问题