定义一个point类,输入10个点坐标。
1.计算出两两点之间的最短、最长距离并输出。
2.计算出10个点的重心坐标。
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
double x;
double y;
Point(double x, double y): x(x), y(y){} //构造函数
double distanceTo(Point &p) { //计算点与点之间的距离
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx * dx + dy * dy);
}
};
int main() {
Point points[10] = {{1.0, 1.0}, {2.0, 2.0}, {3.0, 3.0}, {4.0, 4.0}, {5.0, 5.0},
{6.0, 6.0}, {7.0, 7.0}, {8.0, 8.0}, {9.0, 9.0}, {10.0, 10.0}}; //输入10个点坐标
int n = 10;
//计算两两点之间的最短、最长距离并输出
double minDist = 999999.0, maxDist = -999999.0;
for(int i = 0; i < n; i++) {
for(int j = i+1; j < n; j++) {
double dist = points[i].distanceTo(points[j]);
if(dist < minDist)
minDist = dist;
if(dist > maxDist)
maxDist = dist;
}
}
cout << "最短距离:" << minDist << endl;
cout << "最长距离:" << maxDist << endl;
//计算10个点的重心坐标
double sum_x = 0.0, sum_y = 0.0;
for(int i = 0; i < n; i++) {
sum_x += points[i].x;
sum_y += points[i].y;
}
double centroid_x = sum_x / n;
double centroid_y = sum_y / n;
cout << "重心坐标为:" << "(" << centroid_x << ", " << centroid_y << ")" << endl;
return 0;
}
class Point
{
private:
double x;
double y;
public:
Point(double x=0.0,double y=0.0)
{this->x=x,this->y=y;}
void setdata(double a,double b)
{this->x=a;this->y=b;}
Point operator=(Point a);//重载运算符“=”
int operator==(Point a);//重载运算符“==”
int operator!=(Point a);
double getx()
{return x;}
double gety()
{return y;}
//重载输入流
friend istream &operator>>(istream &is,Point &p)
{
is>>p.x;
is>>p.y;
return is;
}//重载输出流
friend ostream &operator<<(ostream &os,Point p)
{
os<<"("<<p.x<<","<<p.y<<")";
return os;
}
};
inline Point Point::operator=(Point a)
{
this->x=a.x;
this->y=a.y;
return *this;
}
inline int Point::operator==(Point a)
{
if(this->x==a.getx()&&this->y==a.gety())
{
return 1;
}
else {
return 0;
}
}
inline int Point::operator!=(Point a)
{
if(this->x!=a.getx()&&this->y!=a.gety())
{
return 1;
}
else if(this->x!=a.getx()||this->y!=a.gety()){
return 1;
}
else {
return 0;
}
}