一:算法介绍
1. 首先定义两条直线方程:
2. 解方程,求出x, y坐标
3. 如果x分母的行列式等于0, 说明两条直线平行或方向相反
4. 如果x,y分母的行列式都等于0,说明两条线重叠
二:代码实现:
#include <cmath>
#include <iostream>class Point2D {
public:double x, y;
};class Line2D {
public:double a, b, c;
};const double EPS = 1e-9;double det(double a, double b, double c, double d) {return a*d - b*c;
}bool intersect(const Line2D& m, const Line2D& n, Point2D & res) {double zn = det(m.a, m.b, n.a, n.b);if (abs(zn) < EPS)return false;res.x = -det(m.c, m.b, n.c, n.b) / zn;res.y = -det(m.a, m.c, n.a, n.c) / zn;return true;
}bool parallel(const Line2D& m, const Line2D& n) {return abs(det(m.a, m.b, n.a, n.b)) < EPS;
}bool equivalent(const Line2D& m, const Line2D& n) {return abs(det(m.a, m.b, n.a, n.b)) < EPS&& abs(det(m.a, m.c, n.a, n.c)) < EPS&& abs(det(m.b, m.c, n.b, n.c)) < EPS;
}int main()
{Line2D l1(1.0, 1.0, -2.0);Line2D l2(1.0, -1.0, 0.0);Point2D p(0.0, 0.0);intersect(l1, l2, p);std::cout << p.x << "," << p.y << std::endl;
}