已经三角形ABC三个顶点的坐标,A(x1,y1), B(x2,y2), C(x3,y3) , 和另外一点P(x,y) 的坐标,怎么判断在三角形内还是外
虽然做出来了,但是不高效,现在我也不知道高效的方法是什么?哪位大侠告诉小弟。
方法一:求面积之和
public class Mytest02 {
public static void main(String[] args){
double x1=1.0, y1=1.0 ; //A
double x2=3.0, y2=1.0 ; //B
double x3=2.0, y3=3.0 ; //C
double x=2.0, y=2.0 ; //P
double pa = Math.sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1));
double pb = Math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2));
double pc = Math.sqrt((x-x3)*(x-x3)+(y-y3)*(y-y3));
double ab = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
double ac = Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
double bc = Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
double abc = (ab+bc+ac)/2 ;
double pab = (pa+pb+ab)/2;
double pbc = (pb+pc+bc)/2;
double pac = (pa+pc+ac)/2;
System.out.println(abc);
System.out.println(pab);
System.out.println(pbc);
System.out.println(pac);
double sabc = Math.sqrt(abc*(abc-ab)*(abc-bc)*(abc-ac));
double spab = Math.sqrt(pab*(pab-pa)*(pab-pb)*(pab-ab));
double spbc = Math.sqrt(pbc*(pbc-pb)*(pbc-pc)*(pbc-bc));
double spac = Math.sqrt(pac*(pac-pa)*(pac-pc)*(pac-ac));
System.out.println(sabc);
System.out.println(spab);
System.out.println(spbc);
System.out.println(spac);
//判断
if(Math.abs(sabc-(spab+spbc+spac))<0.0000001){
System.out.println("P点在这个三角形内部或者边上");
}else {
System.out.println("P点不在这个三角形外部");
}
}
}
方法二:求角度之和
public class Mytest03 {
public static void main(String[] args){
double x1=1.0, y1=1.0 ; //A
double x2=3.0, y2=1.0 ; //B
double x3=2.0, y3=3.0 ; //C
double x=2.0, y=2.0 ; //P
double pa = Math.sqrt((x-x1)*(x-x1)+(y-y1)*(y-y1));
double pb = Math.sqrt((x-x2)*(x-x2)+(y-y2)*(y-y2));
double pc = Math.sqrt((x-x3)*(x-x3)+(y-y3)*(y-y3));
double ab = Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));
double ac = Math.sqrt((x1-x3)*(x1-x3)+(y1-y3)*(y1-y3));
double bc = Math.sqrt((x2-x3)*(x2-x3)+(y2-y3)*(y2-y3));
double apb = Math.acos((pa*pa+pb*pb-ab*ab)/(2*pa*pb)) ;
double apc = Math.acos((pa*pa+pc*pc-ac*ac)/(2*pa*pc)) ;
double bpc = Math.acos((pb*pb+pc*pc-bc*bc)/(2*pb*pc)) ;
System.out.println(apb) ;
System.out.println(apc) ;
System.out.println(bpc) ;
System.out.println(Math.PI*2) ;
//判断
if(Math.abs(apb+apc+bpc-Math.PI*2)<0.0000001){
System.out.println("P点在这个三角形内部或者边上");
}else {
System.out.println("P点在这个三角形外部");
}
}
}
判断点P在三角形内还是外
最新推荐文章于 2023-03-29 21:46:39 发布