如图所示,本文记录了使用C++代码计算两条线段是否有交点。
图1:

图2:

#include "stdafx.h"
#include "TwoLineSegmentsIntersect.h"
#include<iostream>
#include<algorithm>
using namespace std;
int main()
{
double x1, y1, x2, y2, x3, y3, x4, y4;
x1 = 0.0;
y1 = 0.0;
x2 = 1.0;
y2 = 1.0;
x3 = 0.0;
y3 = 1.0;
x4 = 1.0;
y4 = 0.0;
double startPointofLine1[2] = { x1, y1 };
double endPointofLine1[2] = { x2, y2 };
double startPointofLine2[2] = { x3, y3 };
double endPointofLine2[2] = { x4, y4 };
bool result = judgeWhetherLineSegmentsIntersect(startPointofLine1, endPointofLine1, startPointofLine2, endPointofLine2);
cout << result << endl;
system("pause");
return 0;
}
bool judgeWhetherLineSegmentsIntersect(double startPointofLine1[2], double endPointofLine1[2], double startPointofLine2[2], double endPointofLine2[2])
{
double x1, y1, x2, y2, x3, y3, x4, y4;
double a, b, c, d;//表示向量叉积
x1 = startPointofLine1[0];
y1 = startPointofLine1[1];
x2 = endPointofLine1[0];
y2 = endPointofLine1[1];
x3 = startPointofLine2[0];
y3 = startPointofLine2[1];
x4 = endPointofLine2[0];
y4 = endPointofLine2[1];
a = (x2 - x1) * (y3 - y1) - (y2 - y1) * (x3 - x1);//向量AB * AC的叉积
b = (x2 - x1) * (y4 - y1) - (y2 - y1) * (x4 - x1);//AB * AD
c = (x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3);//CD * CA
d = (x4 - x3) * (y2 - y3) - (y4 - y3) * (x2 - x3);//CD * CB
if (max(x1, x2) < min(x3, x4) || max(x3, x4) < min(x1, x2)
|| max(y1, y2) < min(y3, y4) || max(y3, y4) < min(y1, y2))
return false;
else if (a * b <= 0 && c * d <= 0)
return true;
else
return false;
}