为什么我的阶乘程序打印0?

时间:2015-08-21 14:23:05

标签: java factorial

此代码用于查找100个阶乘和数字中的数字之和。但是,它返回0.

为什么会这样?

public class Problem20 {
  public static void main(String[] args){
    int num = 100;

    for(int i = 1; i< 100; i++){
        num = num * i;
    }

    String numstring = Integer.toString(num);
    int sum = 0;

    for(int j = 0; j < numstring.length(); j++){
        sum += numstring.charAt(j) - '0';
    }
    System.out.print(sum);
  }
}

2 个答案:

答案 0 :(得分:4)

每次乘以2,都会在数字的二进制表示的低位添加0

根据JLS §15.17.1

  

如果整数乘法溢出,则结果是数学乘积的低阶位,如某些足够大的二进制补码格式所示。因此,如果发生溢出,则结果的符号可能与两个操作数值的数学乘积的符号不同。

这里有一些代码来证明这一点。如您所见,数字末尾的0数量缓慢增加;当我们到达32时,低位变为全0。请参阅: Why does this multiplication integer overflow result in zero?

public class Problem20 {
  public static void main(String[] args) {
    int num = 100;

    for (int i = 1; i < 33; i++) {
      num = num * i;
      System.out.println(i + "\t" + Integer.toBinaryString(num));
    }
  }
}

输出:

1   1100100
2   11001000
3   1001011000
4   100101100000
5   10111011100000
6   10001100101000000
7   1111011000011000000
8   1111011000011000000000
9   10001010011011011000000000
10  10101101000010001110000000000
11  11101101111011000011010000000000
12  100111000100100111000000000000
13  11111011111011111011000000000000
14  11000111000110111010000000000000
15  10101010100111100110000000000000
16  10101001111001100000000000000000
17  1001000010001100000000000000000
18  10100111011000000000000000000
19  10001101100001000000000000000000
20  1110010100000000000000000000
21  101100100100000000000000000000
22  11010100011000000000000000000000
23  10100101000000000000000000000
24  11101111000000000000000000000000
25  1010111000000000000000000000000
26  11010110000000000000000000000000
27  10010010000000000000000000000000
28  11111000000000000000000000000000
29  11000000000000000000000000000
30  11010000000000000000000000000000
31  110000000000000000000000000000
32  0

您可以使用BigInteger代替int来解决此问题,例如

import java.math.BigInteger;

public class Problem20 {
  public static void main(String[] args) {
    BigInteger num = BigInteger.valueOf(100);

    for (int i = 1; i < 100; i++) {
      num = num.multiply(BigInteger.valueOf(i));
      System.out.println(num);
    }
  }
}

答案 1 :(得分:2)

好的。

{{1}}

您认为这适合任何这些数据类型吗?

一旦数字越过极限会发生什么?它溢出来了。因此你得到了错误的答案。

那我该怎么办?

使用{{1}}。

相关问题