File tree Expand file tree Collapse file tree
niuke/practice/noob/noob72 点到直线距离 Expand file tree Collapse file tree Original file line number Diff line number Diff line change @@ -18,15 +18,21 @@ struct line {
1818};
1919
2020double getDistance (point P, line L) {
21- // TODO: 计算点P到直线L的距离
22- // 常规方法
23- double dx = L.point_A .x - L.point_B .x ;
24- double dy = L.point_A .y - L.point_B .y ;
25- double k = dy / dx;
26- double b1 = L.point_A .y - k*L.point_A .x ;
27- double distance = fabs (k*P.x - P.y + b1) / sqrt (k*k + 1 );
21+ // 计算点P到直线L的距离
22+ // 使用向量叉积公式: distance = |cross product| / |line length|
23+ // 这个方法适用于所有情况,包括垂直线和水平线
24+ double dx = L.point_B .x - L.point_A .x ;
25+ double dy = L.point_B .y - L.point_A .y ;
26+
27+ // 计算叉积的绝对值: |(B-A) × (A-P)|
28+ double crossProduct = fabs (dx * (L.point_A .y - P.y ) - (L.point_A .x - P.x ) * dy);
29+
30+ // 计算线段长度: |B-A|
31+ double lineLength = sqrt (dx * dx + dy * dy);
32+
33+ // 距离 = 叉积 / 线段长度
34+ double distance = crossProduct / lineLength;
2835 return distance;
29-
3036}
3137
3238int main () {
You can’t perform that action at this time.
0 commit comments