Java:为什么要“做多"数字变成负数? [英] Java: Why does "long" number get negative?

查看:192
本文介绍了Java:为什么要“做多"数字变成负数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码:

    long i = 0;
    while (true) {  
        i += 10*i + 5;
        System.out.println(i);
        Thread.sleep(100);      
    }

为什么几次打印后long i变为负数?如果超出范围,是否应该不会发生错误?

Why does the long i get negative after a few prints? If the range is exceeded, shouldn't an error occur?

推荐答案

如果在最大值之后增加一个数字,Java不会抛出错误.如果您希望拥有这种行为,则可以使用 Math.addExact(long x, long y) 方法.如果传递Long.MAX_VALUE,则此方法将引发ArithmeticException.

Java doesn't throw an error if you increase a number after its maximum value. If you wish to have this behaviour, you could use the Math.addExact(long x, long y) method from Java 8. This method will throw an ArithmeticException if you pass the Long.MAX_VALUE.

Java不会引发异常并且您收到负数的原因与数字的存储方式有关.对于长原语,第一个字节用于指示数字的符号(0->正号,1->负号),其余字节用于数字值.这意味着最大的正值Long.MAX_VALUE将被存储为01111 ... 111(0后跟63位1).由于在Long.MAX_VALUE中添加了数字,由于符号字节变为1,因此将开始接收负整数.这意味着您有数字溢出,但是Java不会引发此错误.

The reason why Java doesn't throw an exception and you receive negative numbers has to do with the way numbers are stored. For a long primitive the first byte is used for indicating the sign of the number (0 -> positive, 1 -> negative), while the rest are used for the numeric value. This means that Long.MAX_VALUE which is the biggest positive value will be stored as 01111...111 (0 followed by 63 bits of 1). Since you add a number to Long.MAX_VALUE you will start receiving negative integers since the sign byte changes to 1. This means you have an numeric overflow, but this error isn't thrown by Java.

这篇关于Java:为什么要“做多"数字变成负数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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