7-2 计算点到直线的距离一一友元函数的应用 (20分)
计算点到直线的距离。首先设计一个点类Point,它有2 个私有数据成员x和y,表示点的坐标。另一个类为直线类Line,它有3 个私有数据成员a,b和c,表示直线方程ax+by+c= 0。这两个类中都说明了一个友元函数dist,用于计算一个点到直线的距离。点(x.y)到直线ax+by+c=0的距离d的计算公式如下:
语法要点: 友元函数的特点。 这是一个编程题模板。请在这里写题目描述。例如:本题目要求读入2个整数A和B,然后输出它们的和。
输入格式:
输入两行,第一行输入两个整数,表示点坐标x,y的值 在第二行中输入直线三个参数,表示直线方程的三个洗漱a,b,c.
输出格式:
计算点到直线的距离保留两位小数。
输入样例:
在这里给出一组输入。例如:
5 5
2 4 3
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class Line;//由于Point中友元函数要用到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 &);//定义友元函数dist
};
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 &);//定义友元函数dist
};
double dist(Point &P,Line &L)//声明友元函数dist:计算两点距离
{
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;//A
cin>>a1>>b1>>c1; //B
Point P(A,B);//C
Line L(a1,b1,c1);//D
if (dist(P, L) == 0) // 一直没通过的一个测试点!就是因为漏了这个!!!
cout << "The distance is: 0";
else
cout << fixed << setprecision(2)<< "The distance is: " << dist(P, L);
// cout<<fixed<<setprecision(2)<<dist(P,L); 原本并没上面的特殊说明距离为0
return 0;
}
遇到问题:
1.一直没法输出正确结果
原因:代码位置错误;我把CD行放在了AB行前面。先定义了这两个类,再输入数据 ,这样C++不会数据输入到类里面的!
解决方法:先输入数据,再定义类,这样数据就进到类里了
2. PTA测试点1一直没法通过
原因:没有列出距离为0的输出!
解决方法:加距离为0的情况