好象不是太简单!
我调试过了,你再调试一下。
function PointToLine(p,p1,p2:Tpoint):real;
// p 是点
// 线段是由点 p1,p2 表示的。
var
r1,r2,rX,Ry:Real;
x,y,A,B,C,A1,B1,C1:integer;
begin
x:=p.x-p1.x;
y:=p.y-p1.y;
r1:=sqrt(x*x+y*y);
Result:=r1;
if (p1.x=p2.x) and (p1.y=p2.y) then exit;
//如果p1 p2 重合,则就是 p 到 p1 的距离
if (p1.x=p2.x) then //垂直线的情况
if (p.y>=min(p1.y,p2.y)) and (p.y<=max(p1.y,p2.y))
then begin
Result:=abs(p1.x-p.x);
exit;
end;
if (p1.y=p2.y) then //水平线的情况
if (p.x>=min(p1.x,p2.x)) and (p.x<=max(p1.x,p2.x))
then begin
Result:=abs(p1.y-p.y);
exit;
end;
//其它情况,线段表示的Ax+By+C直线应为:
// (y2-y1)x + (x1-x2)y + (x2y1-x1y2)=0
A:=p2.y-p1.y;
B:=p1.x-p2.x;
C:=p2.x*p1.y-p1.x*p2.y;
//经过点 p 到线段所表示直线的垂直线的表示:
// A1x + B1y +C1 =0
A1:=B;
B1:=-A;
C1:=A*p.y-B*p.x;
rX:=(C1*b-C*B1)/(A*B1-A1*B);
rY:=-(A*rX+C)/B;
if (rX>=min(p1.x,p2.x)) and (rX<=max(p1.x,p2.x)) and
(rY>=min(p1.y,p2.y)) and (rY<=max(p1.y,p2.y)) then
begin
Result:=sqrt((p.x-rX)*(p.x-rX)+(p.y-rY)*(p.y-rY));
exit;
end;
x:=p.x-p2.x;
y:=p.y-p2.y;
r2:=sqrt(x*x+y*y);
if r2<result then result:=r2;
end;
procedure TForm1.Button4Click(Sender: TObject);
var
r:real;
begin
r:=PointToLine(point(0,0),point(1,-1),point(2,-1));
showmessage(floattostr(r));
r:=PointToLine(point(0,0),point(-1,-1),point(2,-1));
showmessage(floattostr(r));
end;