简体   繁体   English

Java中坐标之间的距离

[英]Distance between coordinates in Java

I'm trying to solve this problem.我正在努力解决这个问题。 Determine the distance between point (x1, y1) and point (x2, y2), and assign the result to pointsDistance.确定点(x1,y1)和点(x2,y2)之间的距离,并将结果赋给pointsDistance。

I'll now present the original code along with my answer to the problem:我现在将提供原始代码以及我对问题的回答:

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);
   }
}

The desired outcomes from the inputs are not printing.输入的预期结果不会打印。 For an example:例如:

My value:我的价值:
1 1
Expected value:期望值:
3 3

Where have I gone wrong?我哪里错了?

Your formula is incorrect.你的公式不正确。 It should be:它应该是:

pointsDistance = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));

This is just an application of the Pythagorean theorem, and Java has a Math.hypot() convenience method that also protects against arithmetic overflow/underflow:这只是勾股定理的一个应用,Java 有一个Math.hypot()方便的方法,也可以防止算术上溢/下溢:

pointsDistance = Math.hypot(x2-x1, y2-y1);

Thanks to @LouisWasserman for the helpful comment.感谢@LouisWasserman的有用评论。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM