java算术
为什么这段代码返回错误的值?
int i=Integer.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);
why this code returns wrong value?
int i=Integer.MAX_VALUE+1;
long l=Integer.MAX_VALUE+1;
System.out.println(l);
System.out.println(i);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
当您将 1 加到
Integer.MAX_VALUE
时,它会溢出并回绕到Integer.MIN_VALUE
。发生这种情况是因为 Java 使用 二进制补码 来表示整数。 4 位示例:
因此,当您向
0111
(最大值)添加 1 时,它会变成1000
,这是最小值。将这个想法扩展到 32 位,它的工作方式是相同的。至于为什么您的
long
也显示不正确的结果,这是因为它对int
执行加法,然后 then 隐式转换为long
。你需要做:When you add 1 to
Integer.MAX_VALUE
it overflows and wraps around toInteger.MIN_VALUE
.This happens because Java uses two's complement to represent integers. An example in 4 bits:
So when you add 1 to
0111
(max) it goes to1000
, and that's the minimum. Expand this idea to 32-bits and it works the same way.As for why your
long
is also showing an incorrect result, it's because it's performing addition onint
s and then implicitly converting tolong
. You need to do:顾名思义,
Integer.MAX_VALUE
是Integer
可用的最大值。在java中,当Integer超过其最大值1(或溢出1)时,其值将为Integer.MIN_VALUE
。请注意,使用 Float 或 Double 不会出现溢出,该值将为 POSITIVE_INFINITY
资源:
As the name says
Integer.MAX_VALUE
is the max value available for anInteger
. In java when an Integer goes over its max value by 1 (or overflows by 1) then its value will beInteger.MIN_VALUE
.Beware, with Float or Double you won't have this overflow, the value will be
POSITIVE_INFINITY
Resources :
您尝试存储无法用此类型 (2^31 - 1) 表示的值,从而导致 32 位整数类型溢出:
You are overflowing the 32 bit integer type here by trying to store a value that cannot be represented by this type (2^31 - 1):
Java整数是32位有符号类型,范围从:-2,147,483,648到2,147,483,647。
您无法像
i=Integer.MAX_VALUE+1;
中那样设置i
整数变量Java integer is 32 bit signed type ranges from: -2,147,483,648 to 2,147,483,647.
You can't set
i
integer variable as you did ini=Integer.MAX_VALUE+1;