题解 | 点到直线距离, 主要是需要叉乘得到三角形面积,然后除以底,就可以得到高,为距离

点到直线距离

https://www.nowcoder.com/practice/1bcdd78060e54812a9c47ebe40c6af65

#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){
    // TODO: 计算点P到直线L的距离,可以使用面积法,叉乘
    // S=0.5*( (x2-x1)*(y3-y1) - (x3-x1)*(y2-y1)) )
    // d = 2*S/点2和3的距离
    return 1.0 *abs( (L.point_A.x-P.x)*(L.point_B.y-P.y) - (L.point_B.x-P.x)*(L.point_A.y-P.y) ) / sqrt( pow(L.point_A.x-L.point_B.x,2) +pow(L.point_A.y-L.point_B.y,2) );
}


int main(){
    int a, b, sx, sy, tx, ty;
    cin >> a >> b >> sx >> sy >> tx >> ty;
    point A(sx, sy), B(tx, ty), C(a, b);
    line L(A, B);
    printf("%.2lf", getDistance(C, L));
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务