点到直线距离计算及g++编译

1、点到直线距离推导

已知两点,a(x1,y1),b(x2,y2),求点c(x3,y3)a,b两点所在直线的距离。

ab两点所在的直线:

  如果不垂直,根据直线上两点间斜率相等有:

  整理后有

 

  类比于: 

  那么,点到直线的距离:

  在三角形cMN中,根据面积相等有:

带入坐标点得:

2、代码

linux系统编写

在终端terminal中执行

 vim calPoint2LineDistance.cpp

在该cpp中写代码如下:

#include<iostream>
#include<stdlib.h>  //abs()
#include<math.h>    //sqrt()

using namespace std;

int main(int argc, char* argv[]){
    //argv: 0 is self, 1,2,3,4,5,6 are x1,y1,x2,y2,x3,y3
    cout<<"argc is:"<<argc<<endl;
    if(argc!=7){
        cout<<"need at least three points"<<endl;
        return 0;
    }
    float x1,y1,x2,y2,x3,y3;
    x1 = *argv[1], y1 = *argv[2], x2 = *argv[3], y2 = *argv[4], x3 = *argv[5], y3 = *argv[6];
    if(x1 == x2){
        cout<<"vertical,point2line distance is:"<<abs(x3-x1)<<endl;
        return abs(x3-x1);
    }
    else{
        float d = abs((y1-y2)*x3+(x2-x1)*y3+(x1*y2-y1*x2))/sqrt(pow(y1-y2,2)+pow(x2-x1,2));
        cout<<"point2line distance is:"<<d<<endl;
        return d;
    }
}

  

3、编译及使用

g++编译:

g++ calPoint2LineDistance.cpp -o calPoint2LineDistance.out

-o 编译选项为将产生的可执行文件用指定的文件名,此处指定的是calPoint2LineDistance.out,不指定的话,默认是a.out。

使用:

./calPoint2LineDistance.out  2 0 0 2 2 2

计算点(2,0)、(0,2)与点(2,2)之间的距离。

 

输出:

argc is:7

point2line distance is:1.41421

 

下载:

calPoint2LineDistance.out 下载地址:https://pan.baidu.com/s/1LOoCcAwwXfF9MVFtEoQIaA ,密码:24a9

 

原文地址:https://www.cnblogs.com/xiaoheizi-12345/p/14255387.html