distanceTo()整数溢出?

问题描述 投票:0回答:3

这是我确定两点之间距离的方法:


    // Euclidean distance between this point and that point
    public int distanceTo(Point that) {
        int distanceX = this.x - that.x;
        int distanceY = this.y - that.y;
        return (int) Math.sqrt(distanceX * distanceX + distanceY * distanceY);
    }

是否有可能发生整数溢出,如果发生,如何防止它?

编辑:

enter image description here

java integer integer-overflow
3个回答
2
投票

为了防止错误的结果溢出,请使用Math“精确”方法:

1]或Math.incrementExact(int a)变体。

如果将发生溢出,则方法将抛出Math.decrementExact(int a)

Math.decrementExact(int a)

当然,使用Math.negateExact(int a)数学来尽量减少溢出的可能性是审慎的做法。

Math.negateExact(int a)

[将Math.toIntExact(long value)扩展为Math.toIntExact(long value)时,精度可能会有所损失,但是当将小数转换为long时,如果舍弃小数,则效果可能会丢失。


0
投票

首先您可以使用ArithmeticException功能。

然后整数溢出可能会在一定距离(public int distanceTo(Point that) throws ArithmeticException { int distanceX = Math.subtractExact(this.x, that.x); int distanceY = Math.subtractExact(this.y, that.y); return (int) Math.sqrt(Math.addExact(Math.multiplyExact(distanceX, distanceX), Math.multiplyExact(distanceY, distanceY))); } )处发生。

解决方案是使用double,因为最终结果是使用浮点函数计算的。

结果可能和long一样大,也溢出了。

所以:

public int distanceTo(Point that) {
    long distanceX = Math.subtractExact((long) this.x, (long) that.x);
    long distanceY = Math.subtractExact((long) this.y, (long) that.y);
    long sumOfSquares = Math.addExact(Math.multiplyExact(distanceX, distanceX),
                                      Math.multiplyExact(distanceY, distanceY));
    return Math.toIntExact((long) Math.sqrt(sumOfSquares));
}

或者更整洁(安德烈亚斯也一样):

sumOfSquares

0
投票

您可以定义一种检查double溢出的方法。快速演示如下:

long

输出:

hypotenuse
© www.soinside.com 2019 - 2024. All rights reserved.