Java方法获得欧几里得距离

use*_*564 4 java methods euclidean-distance

public class Point
{ 
// Placeholders for xcoordinate, ycoordinate, and quadrants
int xcoord = 0;
int ycoord =0;
double distance = 0.0;
String quadrant = ("NW");


//moveUp changes the y coordinate 
void moveUp (int x) {
    int moveUp = ycoord + x;
    ycoord= moveUp;
    System.out.println(moveUp);
    }
// moveDown changes the y coordinate    
void moveDown (int y){
    int moveDown = ycoord - y;
    ycoord =moveDown;
    System.out.println(moveDown);}
// moveLeft changes the x coordinate    
void moveLeft (int f){
    int moveLeft = xcoord -f ;
    xcoord = moveLeft;
    System.out.println(moveLeft);}
// moveRight changes the x coordinate   
void moveRight (int h) {
    int moveRight  = xcoord +h ;
    xcoord = moveRight;
    System.out.println(moveRight);}

//  This takes the y coordinate and the xcoordinate and places it into a quadrant. Then it returns the quadrant.
String quadrant () {    
    if (xcoord >= 0 && ycoord  >=0){
        return quadrant = ("NE"); }
    else if ( xcoord < 0 && ycoord < 0 ) {
        return quadrant = ("SW");}
    else if (xcoord <0 && ycoord >0 ){
        return quadrant = ("NW");}
    else if (xcoord >0 && ycoord <0){
        return quadrant = ("SE");}
    else {
        return quadrant = ("Origin");}  
}
//euclidean distance (?)
Point distance (Point other) {
    Point result = new Point(); 
    result.ycoord = Math.abs (ycoord - other.ycoord);
    result.xcoord = Math.abs (xcoord- other.xcoord);    
    result.distance = Math.sqrt((result.ycoord)*(result.ycoord) +(result.xcoord)*(result.xcoord));
    System.out.println(result);
    return result;

    }

}   
Run Code Online (Sandbox Code Playgroud)

这是整个代码。我遇到麻烦的原因是我的距离方法无法正常工作,我也不知道为什么。它返回Point@24a42c89,而不是任何数字。请让我知道为什么它返回此数字而不是数字。非常感谢。我是一个初学者,对Java知之甚少。

Cod*_*ice 6

Point由于返回Point对象,因此得到一个结果。Point计算两点之间的距离时,没有理由声明一个对象。这里所有计算的结果都是数字,因此将所有变量声明为double

double distance (Point other) {
    double deltaX = ycoord - other.ycoord;
    double deltaY = xcoord - other.xcoord;
    double result = Math.sqrt(deltaX*deltaX + deltaY*deltaY);
    return result; 
}
Run Code Online (Sandbox Code Playgroud)

请注意,Math.abs()由于对两个数进行平方运算始终会得到非负数,因此不需要。

这也消除了distance在每个点中存储值的需要。这应该是有意义,因为一个点是一对(X,Y)坐标,但具有内在的距离。确切地说,“距离”是两点之间的关系。


小智 3

您的方法返回一个 Point,因为您返回result的是 Point 的实例。如果你想要一个双精度(值)的距离,你应该这样做:

//euclidean distance (?)
double distance (Point other) {
    Point result = new Point(); 
    result.ycoord = Math.abs (ycoord - other.ycoord);
    result.xcoord = Math.abs (xcoord- other.xcoord);    
    result.distance = Math.sqrt((result.ycoord)*(result.ycoord) +(result.xcoord)*(result.xcoord));
    System.out.println(result);
    return result.distance; 
    }
} 
Run Code Online (Sandbox Code Playgroud)