计算点到直线的距离。首先设计一个点类Point,它有2 个私有数据成员x和y,表示点的坐标。另一个类为直线类Line,它有3 个私有数据成员a,b和c,表示直线方程ax+by+c= 0。这两个类中都说明了一个友元函数dist,用于计算一个点到直线的距离。点(x.y)到直线ax+by+c=0的距离d的计算公式如下:
注意:
1、main函数中要先输入再创建对象,否则过不了。
2、要考虑距离等于0的特殊情况!
#include<bits/stdc++.h>
using namespace std;
class Point; //对类的引用性说明
class Line;
class Point
{
double x,y;
public:
Point(double x1, double y1) //定义构造函数
{
x=x1,y=y1;
}
friend double dist(Point &, Line &); //定义友元函数
};
class Line
{
double a,b,c;
public:
Line(double a1, double b1, double c1) //定义构造函数
{
a=a1,b=b1,c=c1;
}
friend double dist(Point &, Line &); //定义友元函数
};
double dist(Point &P, Line &L)
{
double dis;
dis=abs((L.a*P.x+L.b*P.y+L.c)/sqrt(L.a*L.a+L.b*L.b));
return dis;
}
int main()
{
int x,y,a,b,c;
cin>>x>>y>>a>>b>>c;
Point P(x,y); //P、L分别是两个类的对象
Line L(a,b,c);
if(dist(P,L)==0) cout<<"The distance is: 0"<<endl;
else cout<<"The distance is: "<<fixed<<setprecision(2)<<dist(P,L)<<endl;
return 0;
}