原理:三角形面积
三角形 S = 1/2 * 底 * 高
鞋带公式速记法
x: x1 x2 a x1
y: y1 y2 b y1画“↘”相乘(对角线向下)- 画“↙”相乘(对角线向上)S = |(x1*y2+x2*b+a*y1)-(x2*y1+a*y2+x1*b)|
题目
你需要实现一个函数,给定平面上的点 (a, b),以及一条由另外两个点 (x_1, y_1) 和 (x_2, y_2) 确定的直线 L,求点 (a, b) 到直线 L 的距离。
首先设一条线L上两点分别为A、B,平面上为P
- 连接AB,从点P做垂直线PO交AB于O
连接AP
此时三点连线形成一个三角形 - 三角形面积 S=1/2 底(AB) 高(PO)
- 三角形面积 S= |(x1*y2+x2*b+a*y1)-(x2*y1+a*y2+x1*b)|
- 联立求PO长度为答案
答案
#include <bits/stdc++.h>
#include <cmath>
using namespace std;
struct point{
double x,y;
point(double A,double B){
x=A,y=B;
}
point() = default;
};
struct line{
point point_A,point_B;
line(point A,point B){
point_A = A,point_B = B;
}
line() = default;
};
double getDistance(point P, line L){
double AB = sqrt(pow(L.point_A.x-L.point_B.x,2)+pow(L.point_A.y-L.point_B.y,2));
double top = abs((P.y-L.point_A.y)*(L.point_B.x-L.point_A.x)-(P.x-L.point_A.x)*(L.point_B.y-L.point_A.y));
return top/AB;
}
最新评论