栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

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

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

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

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/717718.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号