# B 友元类-计算两点间距离

B 友元类-计算两点间距离

Point类中有两个私有数据成员X和Y来表示点的两个坐标(横坐标和纵坐标), 成员函数需要自己定义。

class Distance
{ public:
float Dis(Point & p,Point & q);
};

int main()
{
float x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
Point p(x1,y1), q(x2,y2);
cout<<setiosflags(ios::fixed);
cout<<setprecision(2);
Distance d;
cout<<d.Dis(p,q)<<endl;
return 0;
}

``1.0 1.0 2.0 2.0``

``1.41``

``````#include<stdio.h>
#include<math.h>
int main()
{
double x1,x2,y1,y2;
scanf("%lf%lf%lf%lf",&x1,&y1,&x2,&y2);
printf("%.2lf",sqrt(pow((x1-x2),2)+pow((y1-y2),2)));
return 0;
}
``````

``````#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

class Point
{ public:
Point(float x,float y)
{
X=x;
Y=y;
}
friend class Distance;
private:
float X,Y;
};

class Distance
{ public:
float  Dis(Point & p,Point & q);
};

float Distance::Dis(Point & p,Point & q)
{
float d;
d=sqrt((q.X-p.X)*(q.X-p.X)+(q.Y-p.Y)*(q.Y-p.Y));
return d;
}
int main()
{
float x1,y1,x2,y2;
cin>>x1>>y1>>x2>>y2;
Point  p(x1,y1), q(x2,y2);
cout<<setiosflags(ios::fixed);
cout<<setprecision(2);
Distance  d;
cout<<d.Dis(p,q)<<endl;
return  0;
}``````