[英]Finding distance between two points in the plane, given by cartesian co-ordinates
我知道寻找距离的公式是什么,但是我不明白为什么我的程序无法正常工作? 这是我的代码:
public class Test {
public static void main(String[] args) {
double res = dist(0.0, 0.0, 4.0, 4.0);
System.out.println(res);
}
private static double dist(double x1, double y1, double x2, double y2) {
return Math.sqrt((x2-x1)*(x2-x1)-(y2-y1)*(y2-y1));
}
}
而不是得到4.0,而是得到0.0 ?! 有人可以解释我为什么吗?
您的dist函数中有一个错误。 距离应为平方和的平方根,而不是差值。 将其更改为以下内容。
return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
同样,您的结果应该是4 * sqrt(2)而不是4.0。
该距离约为5.656854
,而不是4。试试Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1))
。 公式为a^2+b^2=c^2
(a平方+ b平方= c平方),因此您需要使用+
而不是-
。 此更改将使其起作用。 否则,您要将负数传递给Math.sqrt()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.