我有一个名为 Line
的类,我想添加一个计算直线切线的方法。
要计算正切,我需要两个点:(x1,y1) 和 (x2,y2),因此它们的正切将为 (y2 - y1)/(x2 - x1)。假设我有两个点,我想计算切线,在某些情况下,切线没有定义(x2 = x1),线平行于y轴)。我希望能够使用这个函数,当它得到一条没有切线的线时,程序不会崩溃而只会显示错误。
我该怎么做?
这是函数(它位于名为 Line
的类中):
double getTangent() {
// defined only if the line is not perpendicular to the horizontal axis.
return (this.end.getY() - this.start.getY()) / (this.end.getX() - this.start.getX());
}
最佳答案
这可以接受吗?
double getTangent() {
if (this.end.getY() == this.start.getY()) {
return 0; // line is parallel to x-axis
}
else if (this.end.getX() == this.start.getX()) {
return Double.NaN; // line is parallel to y-axis, i.e. undefined
}
else {
return (this.end.getY() - this.start.getY()) / (this.end.getX() - this.start.getX());
}
}
关于java - 在 Java 中处理无效输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60901218/