编程语言
首页 > 编程语言> > Java方法获得欧几里德距离

Java方法获得欧几里德距离

作者:互联网

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;

    }

}   

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

解决方法:

您的方法返回一个Point,因为您返回的结果是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; 
    }
} 

标签:euclidean-distance,java,methods
来源: https://codeday.me/bug/20190728/1561084.html