简体   繁体   中英

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.

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
Expected value:
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:

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

Thanks to @LouisWasserman for the helpful comment.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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