Java中的长分区没有按预期工作 [英] Long Division in Java not working as expected

查看:140
本文介绍了Java中的长分区没有按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

class LongDiv{
public static void main(String [] args){

    final long x = 24*60*60*1000*1000;
    final long y = 24*60*60*1000;
    System.out.println(x/y);
}
}

虽然预期答案是1000,但是javac给出了它是5.原因?

although the expected answer is 1000, but the javac gives it as 5. Reason?

推荐答案

您正在创建的长 x 不是你期望的价值。它在整数范围内。要创建多头,请使用:

The long x you are creating isn't the value you expected. It is in the integer range. To create longs, use:

final long x = 24L*60L*60L*1000L*1000L;
final long y = 24L*60L*60L*1000L;
System.out.println(x/y);

您计算的 x ,整数范围, 5006540​​80 。这除以 y (= 86400000 ),结果为 5.794607407407407 ... 。 Java截断导致5的小数部分。

The x you computed, in the integer range, was 500654080. This divided by the y ( = 86400000), results in 5.794607407407407.... Java truncates the decimal part which causes the 5.

通过在数字文字后添加 L ,你告诉编译器将其编译为 long 而不是 int 。您期望的 x 的值是 86400000000 。但是被编译为int。

By adding an L after the number literal, you tell the compiler to compile it as a long instead of an int. The value for x you expected is 86400000000. But is was compiled as an int.

我们可以为 x 重现错误的值( 5006540​​80 )将其截断为int:

We can reproduce the wrong value for x (500654080) by truncating it to an int:

// First correct
long x = 24L*60L*60L*1000L*1000L;
/* x = `86400000000`; */
// Now truncate
x &= 0xFFFFFFFFL; // again: don't forget the L suffix
/* x = `500654080` */

这篇关于Java中的长分区没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆