点到直线的距离.cpp

来自「计算点到直线的距离.输入两点坐标确定一个直线」· C++ 代码 · 共 76 行

CPP
76
字号
#include<iostream>
#include<cmath>
using namespace std;
class CMyLine;//声明类CMyLine,因为CMyPoint类中声明友元函数friend Distance(CMyPoint P,CMyLine L)用到该类 
class CMyPoint
{
	private: 
		double x; 
        double y; 
	public: 
		CMyPoint(double xx=0,double yy=0)//做初始化操作,可以代替无参构造函数
		{ 
			x=xx;  
			y=yy; 
		} 
		double Get_x(){return x;}
		double Get_y(){return y;}
		friend double Distance(CMyPoint P,CMyLine L); 
		friend class CMyLine;
};
class CMyLine
{
	private: 
	    CMyPoint P1,P2;
		double a; 
		double b; 
		double c; 
	public: 
		CMyLine(CMyPoint &P1,CMyPoint &P2) 
		{ 
			if(P2.y>=P1.y)
			{
				a=P2.y-P1.y; 
			    b=P1.x-P2.x; 
	    		c=P1.y*P2.x-P1.x*P2.y; 
			}
			else 
			{
				a=P1.y-P2.y; 
			    b=P2.x-P1.x; 
	    		c=P2.y*P1.x-P2.x*P1.y; 
			}
		} 
		double Get_a(){return a;}
	    double Get_b(){return b;}
		double Get_c(){return c;}
		friend double Distance(CMyPoint P,CMyLine L);  
};



double Distance(CMyPoint P,CMyLine L)
{   
	double s;
	s=fabs(L.Get_a()*P.Get_x()+L.Get_b()*P.Get_y()+L.Get_c())/sqrt(L.Get_a()*L.Get_a()+L.Get_b()*L.Get_b());
	return s;
}
int main()
{
	cout<<"请输入两个点的x和y坐标,以确定直线"<<endl;
	cout<<"第一个点:"<<endl;
	double a,b,c,d,x,y;
    cin>>a>>b;
    cout<<"第二个点:"<<endl;
	cin>>c>>d;
	CMyPoint P1(a,b),P2(c,d); 
	CMyLine L(P1,P2);
	L.Get_a();
	L.Get_b();
	L.Get_c();
	cout<<"请输入一个点的x和y坐标:"<<endl;
    cin>>x>>y;
	CMyPoint P(x,y);
	cout<<"则这点到直线的距离为:"<<Distance(P,L)<<endl;
	return 0;
}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?