点与线的距离及垂足点

<html>
<head>
<meta http-equiv="Content-Type" content="text/html">
<title>点与线的距离及垂足点</title>
</head>

<script language=javascript>
	function dist(x, y, startx, starty, endx, endy)
	{
		var se =  (startx-endx)*(startx-endx)+(starty-endy)*(starty-endy);//线段两点距离平方
		var p = ((x-startx)*(endx-startx)+(y-starty)*(endy-starty)); //向量点乘=|a|*|b|*cosA
		var r = p/se; //r即点到线段的投影长度与线段长度比
		var outx=startx+r*(endx-startx); 
 		var outy=starty+r*(endy-starty); 
  	var des =(x-outx)*(x-outx)+(y-outy)*(y-outy);
		alert(outx);
		alert(outy);
		alert(Math.round(Math.sqrt(des)));
	}
</script>
<body>
	<input type=button value='dist' οnclick="dist()">
<textarea id='textjs' rows="20" cols="120">
dist(5,20,1,6,20,15);
</textarea>
<br>
<input type="button" value="run javacript" οnclick="javascript:eval(textjs.value);">
</body>
<html>

在 C++ 中,计算点到已知直线(由两确定)的距离以及垂足的过程通常涉及到向量的概念和一些几何运算。假设我们有三个 A(x1, y1)、B(x2, y2) 和 C(x, y),其中 AB 是直线的方向向量,C 是需要找到距离。 首先,我们需要计算方向向量 AB 和从起 A 到 C 的向量 AC: AB = B - x1, y2 - y1) AC = C - A = (x - x1, y - y1) 接下来,我们需要找到向量 AB 在 AB 方向上的投影(即平行于直线的分量),这个长度就是 C 到直线距离 d: d = |AB| * dot(AC, AB) / |AB|^2 其中 |AB| 表示 AB 向量的模(长度),dot 表示内积(积),公式中除以 AB 的平方模是为了确保结果是一个数值,而不是一个比例。 然后,我们将 d 除以 AB 的模来得到垂足在原坐标系下的比例因子 t: t = d / |AB| 最后,我们可以计算垂足 D(x', y') 位于直线上的位置,D 的坐标是: x' = x + t * (x2 - x1) y' = y + t * (y2 - y1) 以下是完整的 C++ 代码示例: ```cpp #include <iostream> #include <cmath> struct Point { double x, y; }; double distanceToLine(Point p, Point a, Point b) { Point ab = {b.x - a.x, b.y - a.y}; Point ac = {p.x - a.x, p.y - a.y}; double dot_product = ab.x * ac.x + ab.y * ac.y; double length_ab = std::sqrt(ab.x * ab.x + ab.y * ab.y); return abs(dot_product) / length_ab; } Point perpendicularFoot(Point p, Point a, Point b) { double t = distanceToLine(p, a, b); return {a.x + t * (b.x - a.x), a.y + t * (b.y - a.y)}; } int main() { // 假设A、B和C的坐标分别为... Point A, B, C; double dist = distanceToLine(C, A, B); Point foot = perpendicularFoot(C, A, B); std::cout << "Distance from point C to line AB: " << dist << std::endl; std::cout << "Perpendicular foot on the line at point D: (" << foot.x << ", " << foot.y << ")" << std::endl; return 0; } ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值