[英]Distance between coordinates in Java
我正在努力解决这个问题。 确定点(x1,y1)和点(x2,y2)之间的距离,并将结果赋给pointsDistance。
我现在将提供原始代码以及我对问题的回答:
import java.util.Scanner;
public class CoordinateGeometry {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);
double x1;
double y1;
double x2;
double y2;
double pointsDistance;
double xDist;
double yDist;
pointsDistance = 0.0;
xDist = 0.0;
yDist = 0.0;
x1 = scnr.nextDouble();
y1 = scnr.nextDouble();
x2 = scnr.nextDouble();
y2 = scnr.nextDouble();
pointsDistance = Math.sqrt(x2 - Math.pow(x1, 2) + y2 - Math.pow(y1, 2)); //*Learning Square Rooots and powers*//
System.out.println(pointsDistance);
}
}
输入的预期结果不会打印。 例如:
我的价值:
1
期望值:
3
我哪里错了?
你的公式不正确。 它应该是:
pointsDistance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
这只是勾股定理的一个应用,Java 有一个Math.hypot()
方便的方法,也可以防止算术上溢/下溢:
pointsDistance = Math.hypot(x2-x1, y2-y1);
感谢@LouisWasserman的有用评论。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.