C语言计算点到直线的距离

C语言计算点到直线的距离,第1张

C语言计算点到直线的距离
double dis_calculate(vec2d_t *point, vec2d_t *line_point_1, vec2d_t *line_point_2){
    
    if (line_point_1->x_ == line_point_2->x_) {
        return fabs(point->x_ - line_point_1->x_);
    }
    double k, b;
    k = (line_point_2->y_ - line_point_1->y_) / (line_point_2->x_ - line_point_1->x_);
    b = line_point_2->y_ - line_point_2->x_ * k;
    
    double res = fabs(k*point->x_-point->y_ + b) / sqrt(k*k+1);

    return res;
}

vecd_t结构:x_和y_表示横纵坐标

typedef struct vec2d_s {
	double x_;
	double y_;
}vec2d_t;

完整代码:

#include 
#include 

typedef struct vec2d_s {
	double x_;
	double y_;
}vec2d_t;


double dis_calculate(vec2d_t *point, vec2d_t *line_point_1, vec2d_t *line_point_2){
    
    if (line_point_1->x_ == line_point_2->x_) {
        return fabs(point->x_ - line_point_1->x_);
    }
    double k, b;
    k = (line_point_2->y_ - line_point_1->y_) / (line_point_2->x_ - line_point_1->x_);
    b = line_point_2->y_ - line_point_2->x_ * k;
    
    double res = fabs(k*point->x_-point->y_ + b) / sqrt(k*k+1);

    return res;
}

void main()
{
    vec2d_t p;
    p.x_ =0;
    p.y_ =0;
    vec2d_t point1;
    vec2d_t point2;
    point1.x_ =0;
    point1.y_ =1;
    point2.x_ =1;
    point2.y_ =0;

    double dis = dis_calculate(&p, &point1, &point2);

    printf("dis between p to line is: %lfn", dis);
}

输出结果:

dis between p to line is: 0.707107

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5714044.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-18
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存