gpt4 book ai didi

java - distanceTo() 整数溢出?

转载 作者:行者123 更新时间:2023-12-02 01:04:05 24 4
gpt4 key购买 nike

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


// 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

最佳答案

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

1) 或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)));
}

当然,谨慎使用数学来最小化溢出的可能性。

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 扩大为 double 时,可能会出现少量精度损失,但当在转换为 期间丢弃小数时,效果可能会丢失长

关于java - distanceTo() 整数溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60279057/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com