Description
定义Point类,有2个double类型的属性表示点的横坐标和纵坐标。重载其减法运算符,用于计算两个点之间的距离。
定义PointArray类,是由Point类的对象组成的数组,有如下成员函数:
void append(const Point&):将一个点加入到数组中。
double getMaxDis():计算数组中距离最远的一对点之间的距离。
Input
输入一系列点的坐标,每个点的坐标占一行。
Output
见样例。
Sample Input
1 1
2 2
3 3
4 4
5 5
Sample Output
14.1421
5.65685
HINT
PointArray类中要用Point类重载的减法运算符。
Append Code
int main()
{
Point p, p1(10, 10), p2(20, 20);
PointArray pArr;
double x, y;
while(cin>>x>>y)
{
p.set(x, y);
pArr.append(p);
}
cout<<p2 - p1<<endl;
cout<<pArr.getMaxDis()<<endl;
return 0;
}
Accepted Code
/**
* 2020年6月9日15:46:49
* OJ计算机科学与技术2019-3,4:程序设计基础(2-2)—实验10
*/
#include <iostream>
#include <string>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
class Point {
protected:
double x, y;
public:
Point(double X = 0, double Y = 0) : x(X), y(Y) {}
virtual ~Point() {}
double operator - (const Point &p) {
double d = (x - p.x) * (x - p.x) + (y - p.y) * (y - p.y);
return sqrt(d);
}
void set(double d, double d1) {
x = d; y = d1;
}
};
class PointArray {
vector<Point> point;
public:
void append(const Point& p) {
point.push_back(p);
}
double getMaxDis() {
double d1=0,d2=0;
for(int i=0;i<point.size();i++) {
for(int j=i+1;j<point.size();j++) {
d1 = point[i] - point[j];
d2 = max(d1,d2);
}
}
return d2;
}
};