您的位置:首页 > 其它

点线段的距离函数

2016-05-24 13:28 323 查看
点线段的距离函数

#include <iostream>
#include <cmath>

struct POINT
{
double x;
double y;
};
typedef POINT VECTOR;

struct SEGMENT
{
POINT * pStart;
POINT * pEnd;
};

class Segment
{
public:
POINT * pStart;
POINT * pEnd;
Segment() : pStart(NULL), pEnd(NULL) {}
Segment(POINT * p1, POINT * p2) : pStart(p1), pEnd(p2) {}
double GetLength() const;
double GetDist(const POINT * point) const;
double GetDist(const POINT & point) const;
};
double Segment::GetLength() const
{
if(pStart == NULL || pEnd == NULL)
return 0.0;
return sqrt(pow(pStart->x - pEnd->x, 2) + pow(pStart->y - pEnd->y,2));
}
double Segment::GetDist(const POINT * point) const
{
VECTOR sp = {point->x - pStart->x, point->y - pStart->y};
VECTOR se = {pEnd->x - pStart->x, pEnd->y - pStart->y};
VECTOR es = {-se.x, -se.y};
VECTOR ep = {point->x - pEnd->x, point->y - pEnd->y};
if(sp.x * se.x + sp.y * se.y <= 0)
return sqrt(pow(pStart->x - point->x,2) + pow(pStart->y - point->y,2));
else if(ep.x * es.x + ep.y * es.y <= 0)
return sqrt(pow(pEnd->x - point->x, 2) + pow(pEnd->y - point->y, 2));
else
{
double abs_sp = sqrt(sp.x * sp.x + sp.y * sp.y);
double abs_se = sqrt(se.x * se.x + se.y * se.y);
double cos = (sp.x * es.x + sp.y * es.y)/(abs_sp * abs_se);
return abs_sp * sqrt(1 - cos * cos);
}
}
double Segment::GetDist(const POINT & point) const
{
return GetDist(&point);
}

int main()
{
POINT p1 = {1.0, 2.0};
POINT p2 = {2.0, 2.0};
POINT p3 = {1.5, 4};
Segment pn = Segment(&p1, &p2);
std::cout<<pn.GetDist(p3)<<std::endl;
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: