题解 | 点到直线距离

点到直线距离

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

#include <bits/stdc++.h>
using namespace std;
//计算点到直线的距离

struct point{
    double x,y;
    //结构体中可以有构造函数,与c的区别,c只能有变量
    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的距离
    //指定点的坐标为 P.x P.y ,直线方程为 y - y2 = (y2 - y1 / x2 - x1)*(x - x2);
    //x1,y1,x2,y2分别为 L.point_A.x  L.point_A.y L.point_B.x L.point_B.y
    double result,a,b,c;
    if(L.point_A.x == L.point_B.x ) result = abs(P.x - L.point_A.x );
    else if(L.point_A.y == L.point_B.y ) {
             result = abs(P. y- L.point_A.y );
    }
    else{
            a = (L.point_B.y - L.point_A.y) / ( L.point_B.x -  L.point_A.x);
    b = -1;
    c = (-1*(L.point_B.y - L.point_A.y)*L.point_B.x ) / ( L.point_B.x -  L.point_A.x) +  L.point_B.y;
    result = abs((a*P.x + b*P.y + c)/sqrt(a * a + b * b));
    }
    return result;
};

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;
}

全部评论

相关推荐

axiom15:校友,我感觉你这个简历去华子暑期实习随便去了
点赞 评论 收藏
分享
求求要我吧:你教育经历放在下面干什么,而且27届还是28届啊()另外看你简历有两面,通常来说投递运营岗位一面简历就够了。另外个人总结要写也放在简历最下面,然后你奖项那里是2019年的哇哈哈,那你究竟投递的是社招还是实习?实习的话你是第几届是肯定要写出来的,社招的话你这个工作经历又太短太花了
点赞 评论 收藏
分享
评论
1
1
分享

创作者周榜

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