打卡第二十八天
计算点到直线的距离
一、
1.设计一个点类Point,它有2 个私有数据成员x和y,表示点的坐标
2.直线类Line,它有3 个私有数据成员a,b和c,表示直线方程ax+by+c= 0
3.构建友元函数dist,用于计算一个点到直线的距离
二、
三、
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class Line;
class Point
{
int x,y;
public:
Point(int X=0,int Y=0)
{
x=X;y=Y;
}
int getx(){ return x; }
int gety(){ return y; }
friend double dist(Point &,Line &);
};
class Line
{
int a,b,c;
public:
Line(int A=1,int B=1,int C=1)
{
a=A,b=B;c=C;
}
int geta(){ return a; }
int getb(){ return b; }
int getc(){ return c; }
friend double dist(Point &,Line &);
};
double dist(Point &P,Line &L)
{
double s;
s=abs((L.a*P.x+L.b*P.y+L.c)/sqrt(L.a*L.a+L.b*L.b));
return s;
}
int main()
{
int A,B,a1,b1,c1;
cin>>A>>B;
cin>>a1>>b1>>c1;
Point P(A,B);
Line L(a1,b1,c1);
if (dist(P, L) == 0)
cout << "The distance is: 0";
else
cout << fixed << setprecision(2)<< "The distance is: " << dist(P, L);
}
四、
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class Line;
class Point
{
int x,y;
public:
Point(int X=0,int Y=0)
{
x=X;y=Y;
}
int getx(){ return x; }
int gety(){ return y; }
friend double dist(Point &,Line &);
};
class Line
{
int a,b,c;
public:
Line(int A=1,int B=1,int C=1)
{
a=A,b=B;c=C;
}
int geta(){ return a; }
int getb(){ return b; }
int getc(){ return c; }
friend double dist(Point &,Line &);
};
double dist(Point &P,Line &L)
{
double s;
s=abs((L.a*P.x+L.b*P.y+L.c)/sqrt(L.a*L.a+L.b*L.b));
return s;
}
int main()
{
int A,B,a1,b1,c1;
cin>>A>>B;
cin>>a1>>b1>>c1;
Point P(A,B);
Line L(a1,b1,c1);
if (dist(P, L) == 0)
cout << "The distance is: 0";
else
cout << fixed << setprecision(2)<< "The distance is: " << dist(P, L);
}