在Java中使用距离公式

在Java中使用距离公式,java,formula,distance,Java,Formula,Distance,我需要使用距离公式来检查鼠标和移动对象之间的距离。然而,我的总距离继续只返回1,我不知道为什么 float mouseX = Engine.getMouseX(); //gets X coordinate of the mouse float mouseY = Engine.getMouseY(); //gets Y coordinate of the mouse graphic.setDirection(mouseX,mouseY); //object faces mouse float c

我需要使用距离公式来检查鼠标和移动对象之间的距离。然而,我的总距离继续只返回1,我不知道为什么

float mouseX = Engine.getMouseX(); //gets X coordinate of the mouse
float mouseY = Engine.getMouseY(); //gets Y coordinate of the mouse

graphic.setDirection(mouseX,mouseY); //object faces mouse
float currentX = graphic.getX();  //gets X coordinate of object
float currentY = graphic.getY();  ////gets Y coordinate of object
double distanceX = (Math.pow((currentX - mouseX), 2)); //calculate (x2-x1)^2
double distanceY= (Math.pow((currentY - mouseY), 2)); //calculate (y2-y1)^2
double totalDistance = (Math.pow((distanceX+distanceY), (1/2))); 
//calculate square root of distance 1 + distance 2
System.out.println("totalDistance = "+totalDistance); //prints distance

您应该为所有指数计算指定
double
精度:

double distanceX = (Math.pow((currentX - mouseX), 2.0d));
double distanceY= (Math.pow((currentY - mouseY), 2.0d));
double totalDistance = (Math.pow((distanceX+distanceY), 0.5d));
实际上,总距离的计算是我唯一看到一个巨大潜在问题的地方。你有这个:

double totalDistance = (Math.pow((distanceX+distanceY), (1/2)));

这里的问题是
(1/2)
将被视为整数除法,结果将被截断为0。

您应该为所有指数计算指定
双精度:

double distanceX = (Math.pow((currentX - mouseX), 2.0d));
double distanceY= (Math.pow((currentY - mouseY), 2.0d));
double totalDistance = (Math.pow((distanceX+distanceY), 0.5d));
实际上,总距离的计算是我唯一看到一个巨大潜在问题的地方。你有这个:

double totalDistance = (Math.pow((distanceX+distanceY), (1/2)));

这里的问题是
(1/2)
将被视为整数除法,结果将被截断为0。

在Java中,您可以简单地使用来计算两点之间的距离

    System.out.println(Point2D.distance(0, 3, 4, 0));
    // prints 5.0

在Java中,您可以简单地使用来计算两点之间的距离

    System.out.println(Point2D.distance(0, 3, 4, 0));
    // prints 5.0
可能的重复可能的重复或者更好,使用。或者更好,使用。