也回答了Shortest distance between a point and a line segment,因爲它收集所有語言的解決方案。答案也放在這裏,因爲這個問題具體要求C#解決方案。這是從http://www.topcoder.com/tc?d1=tutorials&d2=geometry1&module=Static修改:
//Compute the dot product AB . BC
private double DotProduct(double[] pointA, double[] pointB, double[] pointC)
{
double[] AB = new double[2];
double[] BC = new double[2];
AB[0] = pointB[0] - pointA[0];
AB[1] = pointB[1] - pointA[1];
BC[0] = pointC[0] - pointB[0];
BC[1] = pointC[1] - pointB[1];
double dot = AB[0] * BC[0] + AB[1] * BC[1];
return dot;
}
//Compute the cross product AB x AC
private double CrossProduct(double[] pointA, double[] pointB, double[] pointC)
{
double[] AB = new double[2];
double[] AC = new double[2];
AB[0] = pointB[0] - pointA[0];
AB[1] = pointB[1] - pointA[1];
AC[0] = pointC[0] - pointA[0];
AC[1] = pointC[1] - pointA[1];
double cross = AB[0] * AC[1] - AB[1] * AC[0];
return cross;
}
//Compute the distance from A to B
double Distance(double[] pointA, double[] pointB)
{
double d1 = pointA[0] - pointB[0];
double d2 = pointA[1] - pointB[1];
return Math.Sqrt(d1 * d1 + d2 * d2);
}
//Compute the distance from AB to C
//if isSegment is true, AB is a segment, not a line.
double LineToPointDistance2D(double[] pointA, double[] pointB, double[] pointC,
bool isSegment)
{
double dist = CrossProduct(pointA, pointB, pointC)/Distance(pointA, pointB);
if (isSegment)
{
double dot1 = DotProduct(pointA, pointB, pointC);
if (dot1 > 0)
return Distance(pointB, pointC);
double dot2 = DotProduct(pointB, pointA, pointC);
if (dot2 > 0)
return Distance(pointA, pointC);
}
return Math.Abs(dist);
}
我數實現在6種不同的語言這裏:http://stackoverflow.com/questions/849211/shortest-distance-between-a-point-and-a-line-segment – 2010-12-14 10:45:06
@oded:你指哪一部分?它被問及答覆了多少次?或者一開始沒有「如何計算」?正如我所說的對不良搜索技能的道歉,但如果無法想象'如何計算'到一開始......好吧。你的鏈接是2幫助人們2互相理解。認爲你完美地理解了我。 – 2010-12-14 10:55:02
@tim:非常感謝你! – 2010-12-14 10:55:28