# 判断与求解平面内两线段的交点的算法与实现

float k = x1·y2-x2·y1;

if (k == 0) {

//平行

} else {

//进一步判断是否相交

}

dx1=x2-x1

dy1=y2-y1

dx2=x4-x3

dy2=y4-y3

dx3=x3-x1

dy3=y3-y1

t1=dx2·dy1-dx1·dy2

t2=dx1·dy3-dx3·dy1

x=(dx1·dx2·dy3-dx1·dy2·x3+dx2·dy1·x1)/(dy1·dx2-dy2·dx1)

=(dx1·dx2·dy3-dx1·dy2·x3+dx2·dy1·x3-dx2·dy1·x3+dx2·dy1·x1)/(dy1·dx2-dy2·dx1)

=x3+(dx1·dx2·dy3-dx2·dx3·dy1)/(dy1·dx2-dy2·dx1)

=x3+dx2·(dx1·dy3-dx3·dy1)/(dy1·dx2-dy2·dx1)

=x3+dx2·t2/t1

y=y3+dy2·(x-x3)/dx2=y3+dy2·t2/t1

Struct Point {

floatx;

floaty;

}

float calculateVectorProduct(PointP1, Point P2, Point P3, Point P4) {

return(P2.x-P1.x) * (P4.y-P3.y) - (P2.y-P1.y) * (P4.x-P3.x);

}

PointcalculateIntersectionPoint(Point A, Point B, Point C, Point D) {

float t1 =calculateVectorProduct(C, D, A, B);

floatt2 = calculateVectorProduct(A, B, A, C);

float x = C.x +(D.x-C.x) * t2 / t1;

float y = C.y +(D.y-C.y) * t2 / t1;

return newPoint(x, y);

}

float min(float Num1, float Num2) {

returnNum1 > Num2 ? Num2 : Num1;

}

float max(float Num1, float Num2) {

returnNum1 > Num2 ? Num1 : Num2;

}

float isBetween(float Num, floatNum1, float Num2) {

floatdeviation =0.1;      //   由于浮点数的精度问题，因此引入误差防止误判

return(Num >= min(Num1, Num2)-deviation && Num <= max(Num1,Num2)+deviation;

}

bool isPointInSegment(Point P1,Point LineStart, Point LineEnd) {

return(isBetween(P1.x, LineStart.x,LineEnd.x)  &&  isBetween(P1.y, LineStart.y,LineEnd.y));

}

bool checkIsPointOnLine(Point P1,Point LineStart, Point LineEnd) {

if(isBetween(LineStart.x-LineEnd.x, 0, 0)) {

returnisBetween(P1.x-LineStart.x, 0, 0);

}else {

floatk = (LineEnd.y-LineStart.y)/(LineEnd.x-LineStart.x);

floatcalculatedY = k * (P1.x-LineEnd.x) + LineEnd.y;

returnisBetween(P1.y-calculatedY, 0, 0);

}

}

Point A = Point(1, 1);

Point B = Point(4, 3);

Point C = Point(2, 1);

Point D = Point(4, 5);

Point E =calculateIntersectionPoint(A, B, C, D);

bool isOnSegment = isPointInSegment(E, A, B) & isPointInSegment(E, C, D);

• 本文已收录于以下专栏：

举报原因： 您举报文章：判断与求解平面内两线段的交点的算法与实现 色情 政治 抄袭 广告 招聘 骂人 其他 (最多只允许输入30个字)