点到直线的距离公式:
将两点式整理可得:
( y1 - y2 ) * x + ( x2 - x1 ) * y + ( x1 * y2 - x2 * y1 ) = 0
两者结合可得:
(其中:fabs是求绝对值,sqrt是开2次根号,pow是求一个数的n次方)
distance = fabs(((y1 - y2) * x0 - (x1 - x2) * y0 + (x1 * y2 - x2 * y1)) / sqrt(pow(y1 - y2, 2) + pow(x1 - x2, 2)));
代码
#pragma warning(disable : 4996)
#include<iostream>
#include <stdio.h>
#include <stdlib.h>
#include "math.h"
#include "memory.h"
using namespace std;
#define KY_MIN(x,y) (x < y ? x : y)
#define KY_MAX(x,y) (x > y ? x : y)
/**
* @brief 单坐标点描述
*/
typedef struct _OPDEVSDK_POS_POINT_ST_
{
float x;
float y;
}OPDEVSDK_POS_POINT_ST;
/**
* @brief 线段描述
*/
typedef struct _OPDEVSDK_POS_LINE_ST_
{
OPDEVSDK_POS_POINT_ST point1;
OPDEVSDK_POS_POINT_ST point2;
}OPDEVSDK_POS_LINE_ST;
double get_distance(OPDEVSDK_POS_LINE_ST& line, OPDEVSDK_POS_POINT_ST& point);
int main() {
OPDEVSDK_POS_LINE_ST line = { {0,0}, {1,1} };
OPDEVSDK_POS_POINT_ST point = { 1,0 };
cout << get_distance(line, point) << endl;
return 0;
}
double get_distance(OPDEVSDK_POS_LINE_ST& line, OPDEVSDK_POS_POINT_ST& point)
{
double x1 = line.point1.x;
double y1 = line.point1.y;
double x2 = line.point2.x;
double y2 = line.point2.y;
double x0 = point.x;
double y0 = point.y;
double distance;
distance = fabs(((y1 - y2) * x0 - (x1 - x2) * y0 + (x1 * y2 - x2 * y1)) / sqrt(pow(y1 - y2, 2) + pow(x1 - x2, 2))); //点到直线公式
return distance;
}
运行结果:文章来源:https://www.toymoban.com/news/detail-626060.html
0.707107
参考文章:一点到另外两点所成直线的距离文章来源地址https://www.toymoban.com/news/detail-626060.html
到了这里,关于C++ 如何求点到直线的距离?(两点式)的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!