// *************************************************************
// Distance.java
// Computes the distance between two points in java
// *************************************************************
import java.util.Scanner;
import java.lang.Math;
public class Distance
{
public static void main (String[] args)
{
double x1, y1, x2, y2; // coordinates of two points
double distance; // distance between the points
//Formula - D=√(x2-x1)^2 + (y2-y1)^2
Scanner scan = new Scanner(System.in);
// Read in the two points
System.out.print ("Enter the coordinates of the first point " +
"(put a space between them): ");
x1 = scan.nextDouble();
y1 = scan.nextDouble();
System.out.print ("Enter the coordinates of the second point: ");
x2 = scan.nextDouble();
y2 = scan.nextDouble();
// Compute the distance
double math = x1-x2 * y1-y2;
// Print out the answer
System.out.print("The distance between (" + x1 + "," + x2 + ") and (" + y1 + "," + y2 + ") is") ;
}
}
我一直遇到错误,我会继续使用可以更快更短的代码。我需要做的就是读取坐标的用户输入,找到它们之间的距离,然后打印答案。
答案 0 :(得分:1)
首先创建您的Point Class。记住这是Java和OOP
class Project < ActiveRecord::Base
has_many: users_projects
has_many: users, through: :user_projects
end
其次,使用距离计算方法
创建Distance类 class Point {
private double x;
private double y;
private String name;
public Point(String n, double xx, double yy) {
this.name = n;
this.x = xx;
this.y = yy;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public String getName() {
return this.name;
}
}
最后修改主要方法如下
public double getEuclideanDistance(Point p, Point q) {
double ed = Math.sqrt((q.getX() - p.getX()) * (q.getX() - p.getX()) + (q.getY() - p.getY()) * (q.getY() - p.getY()));
return ed;
}
答案 1 :(得分:0)
问题是你没有以正确的方式实施距离公式......你有double math = x1-x2 * y1-y2
但根本没有打电话给Math.pow()
或Math.sqrt()
。
尝试实施以下内容: