点线段的距离函数

点线段的距离函数

#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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值