Skip to content
欢迎扫码关注公众号

Java 解惑 -03:长整除

下面的示例代码计算的是一天中的微秒数除以一天中的毫秒数,因为正好差 3 个数量级,理应打印 1000 ,但结果打印的是 5

java
final long MICROS_PER_DAYH = 24 * 60 * 60 * 1000 * 1000; // 一天的微秒数
final long MILLIS_PER_DAYH = 24 * 60 * 60 * 1000; // 一天的毫秒数

System.out.println(MICROS_PER_DAYH / MILLIS_PER_DAYH); // print 5

原因在于 MICROS_PER_DAYH 的计算结果溢出了,超出了整形的边界值。intint 的乘积仍然保存在一个 int 型的变量中,只有在运算结束赋值给一个 long 型的变量时才会提升为 long 型,而此时已经太迟了。

java
System.out.println(MICROS_PER_DAYH); // print 500654080
System.out.println(MILLIS_PER_DAYH); // print 86400000

修正起来也很容易,只需要将计算中的任意一个数值指定为 long 型即可打印正确的结果。

java
final long MICROS_PER_DAYH = 24L * 60 * 60 * 1000 * 1000;
final long MILLIS_PER_DAYH = 24L * 60 * 60 * 1000;

System.out.println(MICROS_PER_DAYH / MILLIS_PER_DAYH); // print 1000

System.out.println(MICROS_PER_DAYH); // print 86400000000
System.out.println(MILLIS_PER_DAYH); // print 86400000

Page Layout Max Width

Adjust the exact value of the page width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the page layout
A ranged slider for user to choose and customize their desired width of the maximum width of the page layout can go.

Content Layout Max Width

Adjust the exact value of the document content width of VitePress layout to adapt to different reading needs and screens.

Adjust the maximum width of the content layout
A ranged slider for user to choose and customize their desired width of the maximum width of the content layout can go.