已知线段上某点与起点的距离,求该点的坐标

文章目录

1. 概述

在实际进行空间几何计算的时候,很难确定直线的方向向量,一般都是知道线段的起点 O O O和终点 E E E。那么显然方向向量为 D = E − O D=E-O D=EO。这时,根据射线的向量方程,线段上某一点P为:
P = O + t D P=O+tD P=O+tD

很显然,这个t值就确定了线段上 P P P的位置。在方向向量由起止点确定,且点在线段内的情况下,t的取值范围为0到1:取值为0时就是起点 O O O,取值为1时就是终点 E E E。进一步,根据相似三角形原则,如果知道 P P P点与起点 O O O的距离为d,则t的取值为:
t = d M o d ( D ) t = \frac{d}{Mod(D)} t=Mod(D)d

其中Mod(D)是向量的模,也就是线段的长度。

2. 实现

具体的C++实现代码如下:

#include <iostream>

using namespace std;

// 2D Point
struct Vector2d
{
public:
	Vector2d()
	{
	}

	Vector2d(double dx, double dy)
	{
		x = dx;
		y = dy;
	}

	// 矢量赋值
	void set(double dx, double dy)
	{
		x = dx;
		y = dy;
	}

	// 矢量相加
	Vector2d operator + (const Vector2d& v) const
	{
		return Vector2d(x + v.x, y + v.y);
	}

	// 矢量相减
	Vector2d operator - (const Vector2d& v) const
	{
		return Vector2d(x - v.x, y - v.y);
	}

	//矢量数乘
	Vector2d Scalar(double c) const
	{
		return Vector2d(c*x, c*y);
	}

	// 矢量点积
	double Dot(const Vector2d& v) const
	{
		return x * v.x + y * v.y;
	}

	//向量的模
	double Mod() const
	{
		return sqrt(x * x + y * y);
	}

	double x, y;
};

void CalPointFromLineWithDistance(const Vector2d & O, const Vector2d & E, double d, Vector2d& P)
{
	Vector2d D = E - O;	
	double t = d / D.Mod();
	P = O + D.Scalar(t);
}

int main()
{
	Vector2d O(1.0, 2.4);
	Vector2d E(10.2, 11.5);
	double d = 5;
	Vector2d P;

	CalPointFromLineWithDistance(O, E, d, P);
	cout << "计算的点为:" << P.x<<'\t' << P.y << '\n'; 

	cout << "验算距离是否为"<<d<<":" <<(P-O).Mod()<< '\n';
}

运行结果如下所示:

求线上的点

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

charlee44

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值