这道java题应该怎么做?
主函数如下:
public static void main(String[] args){
int x1,x,y1;
Scanner scn=new Scanner(System.in);
x1=scn.nextInt();y1=scn.nextInt();
x=scn.nextInt();
Point p1 = new Point(x1,y1);
Point p2 = new Point(x);
System.out.println(String.format("%.2f", p1.distance()));
System.out.println(String.format("%.2f", p2.distance()));
System.out.println(String.format("%.2f", p1.distance(6,8)));
System.out.println(String.format("%.2f", p1.distance(p2)));
}
输入
输入两个点
输出
点之间的距离
难度
一般
输入示例
3 4
5
输出示例
5.00
7.07
5.00
2.24 展开
Java源代码:
public class Test {
public static void main(String[] args) {
Point p1 = new Point(4, 5);
System.out.printf("点p坐标为(%f,%f)\n", p1.getX(), p1.getY());
p1.setX(3);
p1.setY(4);
System.out.printf("重置后点p坐标为(%f,%f)\n", p1.getX(), p1.getY());
System.out.printf("点(%f, %f)到原点的距离的平方为%f\n", p1.getX(), p1.getY(),
p1.distance());
Point p2 = new Point(1, 2);
System.out.printf("点(%f,%f)到点(%f,%f)的距离的平方为%f\n", p1.getX(),
p1.getY(), p2.getX(), p2.getY(), p1.distance(p2));
}
}
class Point {
protected double x;
protected double y;
public Point(){
}
public Point(double x, double y) {
this.x = x;
this.y = y;
}
public void setX(double x) {
this.x = x;
}
public double getX() {
return this.x;
}
public void setY(double y) {
this.y = y;
}
public double getY() {
return this.y;
}
public double distance() {
return Math.pow(x, 2) + Math.pow(y, 2);
}
public double distance(Point p) {
return Math.pow(this.x - p.x, 2) + Math.pow(this.y - p.y, 2);
}
}
运行测试:
private int x;
private int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public Point(int x) {
this(x, x);
}
public int getX() {
return x;
}
public int getY() {
return y;
}
public double distance(int x, int y) {
return Math.sqrt(Math.pow(x - this.x, 2) + Math.pow(y - this.y, 2));
}
public double distance(Point p) {
return distance(p.getX(), p.getY());
}
public double distance() {
return distance(0, 0);
}
public static void main(String[] args) {
int x1, x, y1;
Scanner scn = new Scanner(System.in);
x1 = scn.nextInt();
y1 = scn.nextInt();
x = scn.nextInt();
Point p1 = new Point(x1, y1);
Point p2 = new Point(x);
System.out.println(String.format("%.2f", p1.distance()));
System.out.println(String.format("%.2f", p2.distance()));
System.out.println(String.format("%.2f", p1.distance(6, 8)));
System.out.println(String.format("%.2f", p1.distance(p2)));
}
}
谢谢,我已经会了
广告 您可能关注的内容 |