首页 > 代码库 > 判断点在线段上

判断点在线段上

2016-11-0921:00:46

判断点p0是否在线段p1p2上
1.先判断p0,p1,p2三点共线
2.在判断点p0在以p1p2为对角线的矩形内。

#include <iostream>
#include <algorithm>
using namespace std;

const double inf = 1e-10;
struct point {
    double x, y;
};

struct v {
    point start, end;
};

bool onSegment(point p1, point p2, point p0) {
    if (fabs((p1.x - p2.x)*(p1.y - p0.y) - (p1.x - p0.x)*(p1.y - p2.y))<1e-10 &&
        min(p1.x, p2.y) <= p0.x&&max(p1.x, p1.x) >= p0.x&&
        min(p1.y, p2.y) <= p0.y&&max(p1.y, p2.y) >= p0.y
        )
        return true;
    return false;
}

int main() {
    point p1, p2, p3;
    while (cin >> p1.x >> p1.y >> p2.x >> p2.y >> p3.x >> p3.y) {
        cout << onSegment(p1, p2, p3) << endl;
    }
}

 

判断点在线段上