标签:
1 struct Point 2 { 3 double x, y; 4 }; 5 6 bool between(double a, double X0, double X1) 7 { 8 double temp1= a-X0; 9 double temp2= a-X1; 10 if ( ( temp1<1e-8 && temp2>-1e-8 ) || ( temp2<1e-6 && temp1>-1e-8 ) ) 11 { 12 return true; 13 } 14 else 15 { 16 return false; 17 } 18 } 19 20 21 // 判断两条直线段是否有交点,有则计算交点的坐标 22 // p1,p2是直线一的端点坐标 23 // p3,p4是直线二的端点坐标 24 bool detectIntersect(Point p1, Point p2, Point p3, Point p4) 25 { 26 double line_x,line_y; //交点 27 if ( (fabs(p1.x-p2.x)<1e-6) && (fabs(p3.x-p4.x)<1e-6) ) 28 { 29 return false; 30 } 31 else if ( (fabs(p1.x-p2.x)<1e-6) ) //如果直线段p1p2垂直与y轴 32 { 33 if (between(p1.x,p3.x,p4.x)) 34 { 35 double k = (p4.y-p3.y)/(p4.x-p3.x); 36 line_x = p1.x; 37 line_y = k*(line_x-p3.x)+p3.y; 38 39 if (between(line_y,p1.y,p2.y)) 40 { 41 return true; 42 } 43 else 44 { 45 return false; 46 } 47 } 48 else 49 { 50 return false; 51 } 52 } 53 else if ( (fabs(p3.x-p4.x)<1e-6) ) //如果直线段p3p4垂直与y轴 54 { 55 if (between(p3.x,p1.x,p2.x)) 56 { 57 double k = (p2.y-p1.y)/(p2.x-p1.x); 58 line_x = p3.x; 59 line_y = k*(line_x-p2.x)+p2.y; 60 61 if (between(line_y,p3.y,p4.y)) 62 { 63 return true; 64 } 65 else 66 { 67 return false; 68 } 69 } 70 else 71 { 72 return false; 73 } 74 } 75 else 76 { 77 double k1 = (p2.y-p1.y)/(p2.x-p1.x); 78 double k2 = (p4.y-p3.y)/(p4.x-p3.x); 79 80 if (fabs(k1-k2)<1e-6) 81 { 82 return false; 83 } 84 else 85 { 86 line_x = ((p3.y - p1.y) - (k2*p3.x - k1*p1.x)) / (k1-k2); 87 line_y = k1*(line_x-p1.x)+p1.y; 88 } 89 90 if (between(line_x,p1.x,p2.x)&&between(line_x,p3.x,p4.x)) 91 { 92 return true; 93 } 94 else 95 { 96 return false; 97 } 98 } 99 }
参考 http://blog.csdn.net/llkk890320/article/details/25886613
本想用第三个算法的(追求效率),但是第三个算法是有问题的!
标签:
原文地址:http://www.cnblogs.com/panazhiyong/p/4443287.html