直线求交点公式及代码
直线求交点
题目链接:https://www.acwing.com/problem/content/3693/
1. 直线的表示
直线标准形式:Ax + By = C
设直线经过的两个点为(x1, y1),(x2, y2)
则:
A = y2 - y1
B = x1 - x2
C = A * x1 + B * y1
2. 两条直线求交点
设两条直线方程为:A1x + B1y = C1
A2x + B2y = C2
特殊情况:
-
两条直线有0个交点,即两条直线不同且平行
如果两条直线平行,则
A1 * B2 == A2 * B1
-
两条直线有无穷多个交点,即两条直线相同:
即
A1 == A2;B1 == B2;C1 == C2
设两条直线的交点为(x0, y0)
则:x0 = (B2 * C1 - B1 * C2) / (A1 * B2 - A2 * B1)
y0 = (A1 * C2 - A2 * C1) / (A1 * B2 - A2 * B1)
3. C++代码实现:
#include <bits/stdc++.h>
using namespace std;
#define rep(i,a,b) for(int i = a;i < b;i++)
#define per(i,a,b) for(int i = b - 1;i >= a;i--)
#define all(x) (x).begin(),(x).end()
#define fi first
#define se second
typedef long long ll;
typedef pair<int,int> PII;
typedef vector<int> VI;
const int INF = 0x3f3f3f3f;
const double eps = 1e-4;
int main() {
int x1, y1, x2, y2, x3, y3, x4, y4;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
scanf("%d%d%d%d", &x3, &y3, &x4, &y4);
int A1 = y2 - y1, B1 = x1 - x2, C1 = A1 * x1 + B1 * y1;
int A2 = y4 - y3, B2 = x3 - x4, C2 = A2 * x3 + B2 * y3;
if((A1 * B2 == A2 * B1) || (A1 == A2 && B1 == B2 && C1 == C2)) {
puts("Parallel or coincident");
return 0;
}
double x0 = 1.0 * (B2 * C1 - B1 * C2) / (A1 * B2 - A2 * B1);
double y0 = 1.0 * (A1 * C2 - A2 * C1) / (A1 * B2 - A2 * B1);
if(abs(x0) < eps) x0 = 0;
if(abs(y0) < eps) y0 = 0;
printf("%.2lf %.2lf\n", x0, y0);
return 0;
}
你只管出发,旅途自有风景~~