题目意思比较清楚,给你四个点,组成两条直线,判断直线是否有交点,有交点就求出来,否则就判断是不相交还是重合。
注意点: 判断直线相交的时候要判断斜率不存在的情况。
会求斜率就行了。
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<iostream>
#include<queue>
#include<map>
#include<vector>
#include<set>
#include<string>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
const int INF = 0x3f3f3f3f;
#define endl '\n'
#define pb(a) push_back(a)
#define al(x) x.begin(), x.end()
#define sz(x) int(x.size())
#define IOS ios::sync_with_stdio(0);
struct Point {
int x, y;
Point(int x = 0, int y = 0): x(x), y(y) {}
};
Point operator - (const Point&A, const Point&B) {
return Point(A.x - B.x, A.y - B.y);
}
struct Line { //直线定义
Point v, p;
Line() {}
Line(Point v, Point p): v(v), p(p) {}
} line[2];
int n;
int Cross(Point A, Point B) {
return A.x * B.y - A.y * B.x;
}
int ok(Point A, Point B, Point C, Point D) {
// return: -1:相交 1:不相交 0:重合
// 其中一条直线垂直x轴
if ((A.x == B.x && C.x != D.x) || (A.x != B.x && C.x == D.x)) {
return -1;
}
// 两条都垂直x轴
if (A.x == B.x && C.x == D.x) {
return A.x == C.x ? 0 : 1;
}
// 计算斜率
double k1 = 1.0 * (B.y - A.y) / (B.x - A.x);
double k2 = 1.0 * (D.y - C.y) / (D.x - C.x);
if (k1 != k2) return -1;
if (A.y - k1 * A.x == C.y - k2 * C.x) return 0;
return 1;
}
void solve(Line A, Line B) {
Point a = A.p, b = A.v, c = B.p, d = B.v;
int f = ok(a, b, c, d);
if (f == 1) puts("NONE");
else if (!f) puts("LINE");
else {
// 处理垂直的情况
if (a.x == b.x) {
double b2 = 1.0 * Cross(d, c) / (d.x - c.x);
double k2 = 1.0 * (d.y - c.y) / (d.x - c.x);
double y = 1.0 * k2 * a.x + b2;
printf("POINT %.2f %.2f\n", 1.0 * a.x, y);
} else if (c.x == d.x) {
double b1 = 1.0 * Cross(b, a) / (b.x - a.x);
double k1 = 1.0 * (b.y - a.y) / (b.x - a.x);
double y = 1.0 * k1 * c.x + b1;
printf("POINT %.2f %.2f\n", 1.0 * c.x, y);
} else {
double b1 = 1.0 * Cross(b, a) / (b.x - a.x);
double b2 = 1.0 * Cross(d, c) / (d.x - c.x);
double k1 = 1.0 * (b.y - a.y) / (b.x - a.x);
double k2 = 1.0 * (d.y - c.y) / (d.x - c.x);
double x = -1.0 * (b2 - b1) / (k2 - k1);
double y = 1.0 * k1 * x + b1;
printf("POINT %.2f %.2f\n", x, y);
}
}
}
int main() {
Point a, b, c, d;
scanf("%d", &n);
puts("INTERSECTING LINES OUTPUT");
for (int i = 0; i < n; ++i) {
scanf("%d%d%d%d%d%d%d%d", &a.x, &a.y, &b.x, &b.y, &c.x, &c.y, &d.x, &d.y);
line[0] = Line(a, b);
line[1] = Line(c, d);
solve(line[0], line[1]);
}
puts("END OF OUTPUT");
return 0;
}