diwulechao

点到线段的距离的模板

double xmult(double x1,double y1,double x2,double y2,double x0,double y0)
是算叉乘的
double area_triangle(double x1,double y1,double x2,double y2,double x3,double y3)
是算面积的
double dis_ptoline(double x1,double y1,double x2,double y2,double ex,double ey,double *px,double *py)
自己编的 算点到线段距离的

double xmult(double x1,double y1,double x2,double y2,double x0,double y0){
    
return (x1-x0)*(y2-y0)-(x2-x0)*(y1-y0);
}

double area_triangle(double x1,double y1,double x2,double y2,double x3,double y3){
    
return fabs(xmult(x1,y1,x2,y2,x3,y3))/2;
}

double dis_ptoline(double x1,double y1,double x2,double y2,double ex,double ey,double *px,double *py)
//第一个点,第二个点,目标点  ax ay为答案点  返回距离
    double k,b,dis,tem1,tem2,t1,t2,yd=sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
    t2
=sqrt((x2-ex)*(x2-ex)+(y2-ey)*(y2-ey));
    t1
=sqrt((x1-ex)*(x1-ex)+(y1-ey)*(y1-ey));
    dis
=area_triangle(x1,y1,x2,y2,ex,ey)*2/yd;
    tem1
=sqrt(t1*t1-dis*dis);
    tem2
=sqrt(t2*t2-dis*dis);
    
    
if (tem1>yd||tem2>yd) {
        
if (t1>t2) {*px=x2;*py=y2;return t2;}
        
else {*px=x1;*py=y1;return t1;}
    }

    
*px=x1+(x2-x1)*tem1/yd;
    
*py=y1+(y2-y1)*tem1/yd;
    
return dis;
}

posted on 2008-05-25 15:12 diwulechao 阅读(1786) 评论(2)  编辑 收藏 引用

评论

# re: 点到线段的距离的模板 2009-06-19 11:56 WinterLegend

您这个方法好,先算最短的距离,再去算点。
我是联立直线方程算点,然后计算距离,要讨论斜率,还要推公式,很麻烦。。
看到您写的恍然大悟~  回复  更多评论   

# re: 点到线段的距离的模板 2011-05-06 15:33 age

借用了。多謝~  回复  更多评论   


只有注册用户登录后才能发表评论。
网站导航:   博客园   博客园最新博文   博问   管理


<2026年6月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

导航

统计

常用链接

留言簿

文章档案

搜索

最新评论