您的位置:首页 > 编程语言 > C语言/C++

C++:友元1(两点之间的距离)

2016-01-08 18:49 477 查看

C++:友元1(两点之间的距离)

题目描述:

Description

定义一个二维平面中的点(point)类,类中的数据成员为点的坐标,然后定义友元函数dist()用来计算两点之间的距离。

将下面的程序1 和程序2填写完整。

程序1 :

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
……………………………………
……………………………………
……………………………………
int main()
{
int n;
double x1,x2,y1,y2;
cin>>n;
while (n--)
{
cin>>x1>>y1>>x2>>y2;
point p1(x1,y1),p2(x2,y2);
cout<<fixed<<setprecision(3)<<dist(p1,p2)<<endl;
}
return 0;
}


程序2:

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
……………………………………
……………………………………
……………………………………
int main()
{   int n;    double x1,x2,y1,y2; test t;
cin>>n;
while (n--)
{   cin>>x1>>y1>>x2>>y2;
point p1(x1,y1),p2(x2,y2);
cout<<fixed<<setprecision(3)<<t.dist(p1,p2)<<endl;
}
}


Input

输入包含n组测试例, 第1行是测试组数。

第2行–第n+1行为测试数据,每组测数据有4个实数,表示 2个点的坐标(x1,y1)和(x2,y2)。

Output

两点之间的距离(保留3位小数)。

Sample Input

2

0 0 3 4

1 1 2 2

Sample Output

5.000

1.414

代码块:

#include <iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class point
{
double x,y,d,m;
public:
point(double r=0 , double i=0);
friend point dis(point b, point c);
void show();
};
point::point(double r, double i)
{
x = r;
y = i;
}
void point::show()
{
double d=0,m=0;

cout<<fixed<<setprecision(3)<<sqrt(x+y)*1.0<<endl;

}

point dis(point b, point c)
{
double x1, y1;
x1 = (b.x - c.x)* (b.x - c.x);
y1 = (b.y - c.y)*(b.y - c.y);
return point (x1,y1);
}

int main()
{
double a,b,c,d;
int n;
cin>>n;
for(int i=0;i<n;i++)
{
while (cin>>a>>b>>c>>d)
{
point c1(a,b),c2(c,d),c3,c4;
c3 =dis(c1, c2);
c3.show();
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: