This question already has answers here:
Calculating the distance between two points
                                
                                    (7个答案)
                                
                        
                                4年前关闭。
            
                    
我需要计算出每个士兵之间的距离,但是我无法解决该怎么做,因为它们都来自相同的xPos和yPos,我在网上找到的所有内容都是针对x1,y1,x2,y2的情况。

他们的想法是它们随机产卵,然后可以移动来攻击对方,但我需要知道它们之间的距离,然后才能继续

public class Soldier {

    double xPos;
    double yPos;

    public Soldier(/*double distance, double speed*/) {
        double lower = 0;
        double upper = 100; //setting the upper and lower limits for the soldiers
        xPos = Math.random() * (upper - lower) + lower;
        yPos = Math.random() * (upper - lower) + lower; //creating x and y values
        xPos = Math.round(xPos * 10) / 10.0d;
        yPos = Math.round(yPos * 10) / 10.0d; //making sure the x and y value is to 1dp
        System.out.println("(" + xPos + ", " + yPos + ")"); //printing the location
    }
}


我的主要课程是

public class Main {
   public static void main(String[] args) {
       Soldier Cavalier = new Soldier(/*5.9, 1*/);
       Soldier Pikeman = new Soldier(/*10.3, 12.6*/);
       Soldier Crossbowman = new Soldier(/*4.9, 3*/);
       System.out.println();
   }
}

最佳答案

在士兵类上添加distanceTo方法:

public class Soldier {
    ....

    public double distanceTo(Soldier other) {
        return Math.sqrt(Math.pow(other.xPos-this.xPos,2) + Math.pow(other.yPos-this.yPos,2));
    }
}


然后像这样使用它:

   Soldier Cavalier = new Soldier();
   Soldier Pikeman = new Soldier();
   System.out.println(Cavalier.distanceTo(Pikeman));




由于评论者的建议而添加:

仅需提及,Math.pow是幂函数的通用实现,能够计算任何类型的参数的幂。因此,它比简单的x * x类型乘法要慢得多。此代码的优化版本如下所示:

    public double distanceTo(Soldier other) {
        double dx = other.xPos-this.xPos;
        double dy = other.yPos-this.yPos;
        return Math.sqrt(dx*dx + dy*dy);
    }


如果不需要性能优化,则可以使用更易读的版本。

10-07 22:45