这是我确定两点之间距离的方法:
// 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);
}
是否有可能发生整数溢出,如果发生,如何防止它?
编辑:
为了防止错误的结果溢出,请使用Math
“精确”方法:
Math.addExact(int x, int y)
1Math.addExact(int x, int y)
1Math.subtractExact(int x, int y)
1Math.subtractExact(int x, int y)
1Math.multiplyExact(int x, int y)
1Math.multiplyExact(int x, int y)
1Math.incrementExact(int a)
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
时,如果舍弃小数,则效果可能会丢失。
首先您可以使用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