#include<stdio.h>
typedef struct
{
float x;
float y;
}Point;
typedef struct
{
Point p1;
Point p2;
}Line_segment;
void initLine (Line_segment &L)
{
Point p;
if(L.p1.x>L.p2.x)
{
p=L.p1;
L.p1=L.p2;
L.p2=p;
}
}
Point getNearstPoint(Line_segment L,Point P)
{
Point nearest_p;
float l_k = (L.p1.y-L.p2.y)/(L.p1.x-L.p2.x);//斜率
float v_k = -1/l_k;//与线段垂直的斜率
float h_x = (L.p1.y+v_k*P.x-P.y-l_k*L.p1.x)/(v_k-l_k);//求出线段对应的直线和过p点且与线段对应直线垂直的交点
float h_y =v_k*(h_x-P.x)+P.y;
if(h_x>L.p2.x)
{ //交点的x大于右端端点的x,最近的点就是右端点
nearest_p = L.p2;
}else if(h_x<L.p1.x)
{ //交点的x小于左端端点的x,最近的点就是左端点
nearest_p = L.p1;
}else
{
nearest_p.x=h_x;
nearest_p.y = h_y;
}
return nearest_p;
}
int main() {
Point P;
P.x = 1;
P.y = 1;
Line_segment L;
L.p2.x = 1;
L.p2.y=3;
L.p1.x =0;
L.p1.y = 4;
initLine(L);
Point nearest_p = getNearstPoint(L,P);
printf("intersection x is %f,y is %f", nearest_p.x, nearest_p.y);
getchar();
}
已知一条线段的两端点A(x1,y1),B(x2,y2)及线段外的任意一点P(px,py),设计一个程序找出线段中距离p最近的点
最新推荐文章于 2024-07-29 20:33:46 发布