首页 > 解决方案 > java中2个6位数字的乘法

问题描述

为什么下面代码的输出输出的是 1345094336 而不是 39999800000?我应该如何编辑它?我相信这与整数溢出有关。

public class testC {
    public static void main(String[] args) {
        long product = 199999 * 200000;
        System.out.println(product);
    }
}

标签: java

解决方案


两个整数 199999 * 200000 的乘积是 39999800000,大于整数

storage capacity.
          width                     minimum                         maximum

SIGNED
byte:     8 bit                        -128                            +127
short:   16 bit                     -32 768                         +32 767
int:     32 bit              -2 147 483 648                  +2 147 483 647
long:    64 bit  -9 223 372 036 854 775 808      +9 223 372 036 854 775 807

UNSIGNED
char     16 bit                           0                         +65 535

因此,您需要在乘法端将至少一个数字转换为 long

(long)199999 * 200000
199999 * (long)200000
199999 * 200000L
199999L * 200000

推荐阅读