作业帮 > 综合 > 作业

java由三点求三角形的周长

来源:学生作业帮 编辑:神马作文网作业帮 分类:综合作业 时间:2024/11/19 02:09:47
java由三点求三角形的周长
public class Point {
int x;
int y;
Point(){
}
Point(int a,int b){
x=a;
y=b;
}
}
public class Triangle {
Point n1,n2,n3;
Triangle(Point n1,Point n2,Point n3){
n1=new Point();
n2=new Point();
n3=new Point();
}
double x1=Math.pow(n1.x-n2.x,2)+Math.pow(n1.y-n2.y,2);
double x2=Math.pow(n1.x-n3.x,2)+Math.pow(n1.y-n3.y,2);
double x3=Math.pow(n2.x-n3.x,2)+Math.pow(n2.y-n3.y,2);
double getPerimeter(){
return Math.sqrt(x1)+Math.sqrt(x2)+Math.sqrt(x3);
}
}
public class Test {
public static void main(String[] args) {
Point n1=new Point(0,0);
Point n2 =new Point(0,3);
Point n3=new Point(4,0);
Triangle sanjiao=new Triangle(n1,n2,n3);
System.out.println(sanjiao.getPerimeter());
}
}
java由三点求三角形的周长
你的Triangle构造方法里面传入三个参数都没用到.而且你现在的代码很不符合JAVA面向对象,点之间距离应该是Point里面的方法才合适吧.在你的基础上修改如下:
class Point {
int x;
int y;
Point() {
}
Point(int a,int b) {
x = a;
y = b;
}
public static double getInstance(Point p1,Point p2) {
return Math.sqrt(Math.pow(p1.x - p2.x,2) + Math.pow(p1.y - p2.y,2));
}
}
class Triangle {
Point n1,n2,n3;
Triangle(Point n1,Point n2,Point n3) {
this.n1 = n1;
this.n2 = n2;
this.n3 = n3;
}
public double getPerimeter() {
return Point.getInstance(n1,n2) + Point.getInstance(n1,n3) + Point.getInstance(n2,n3);
}
}
public class Test {
public static void main(String[] args) {
Point n1 = new Point(0,0);
Point n2 = new Point(0,3);
Point n3 = new Point(4,0);
Triangle sanjiao = new Triangle(n1,n2,n3);
System.out.println(sanjiao.getPerimeter());
}
}
--------------
12.0