MT1593
-点到线的最短距离即垂足坐标
一、根据两点求直线方程
已知直线上两点为:(x1,x2),(y1,y2);
设方程为:Ax+By+C=0;
-
求斜率:
k=(y2-y1)/(x2-x1);
-
直线方程为:
y-y1=k(x-x1);
换算得:kx-y+y1-kx1=0
,即:
A=k
B=-1
C=y1-kx1=y1-(y2-y1)/(x2-x1)*x1
二、求距离和垂足公式
- 点
(x0,y0)
到直线的距离公式为:
d=abs(Ax0+By0+C)/sqrt(A*A+B*B);
- 设垂足为p,则:
p.x=(B*B*x0-A*B*y0-A*C)/(A*A+B*B)
p.y=(A*·A*y0-A*B*x0-B*C)/(A*A+B*B)
三、 代码
[码题集](码蹄集 (matiji.net))
ACcode
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
#define MAX_NUM 10005
#define PI 3.1415926
double res;
int ans, n, m, t, k,len, cnt = 0, minn = MAX_NUM,maxx = 0;
char ch, s1[MAX_NUM] = "", s2[MAX_NUM] = "";
bool flag = false;
//int a[MAX_NUM]= {0}, b[MAX_NUM]= {0};
struct Point{
int x, y;
}point[5];
struct Line {
Point s, e;
}line;
double getDistance(Point point, Line line) {
int x1,x2,y1,y2,x0,y0;
x1 = line.s.x;
y1 = line.s.y;
x2 = line.e.x;
y2 = line.e.y;
x0 = point.x;
y0 = point.y;
// ①求斜率 进而求出直线方程
double k, a, b, c, dist;
k = (x1==x2 ? 10000 : (y2-y1)*1.0/(x2-x1)); //当斜率不存在是设置为一个较大的数
a = k;
b = -1;
c = y1-k*x1;
// ②求点到直线的最短距离
dist = abs(a*x0 + b*y0+c)*1.0 / sqrt(a*a+b*b);
// return dist;
// ③求垂足点坐标
double px, py;
px = (b*b*x0-a*b*y0-a*c)*1.0 / (a*a + b*b);
py = (a*a*y0-a*b*x0-b*c)*1.0 / (a*a + b*b);
printf("(%.2lf,%.2lf)\n",px,py);
return dist;
}
int main() {
for(int i = 1; i <= 3; i++) {
cin >> point[i].x >> point[i].y;
}
line.s = point[1];
line.e = point[2];
res = getDistance(point[3], line);
cout << fixed << setprecision(2) << res << endl;
return 0;
}
//-20 20
//20 -10
//-20 20