本文共 2702 字,大约阅读时间需要 9 分钟。
在许多应用中,我们需要定位一个目标点A的坐标。假设已知A点与N个点相邻,并且已知这N个相邻点的坐标。我们可以将这N个点的质心作为A点坐标的一个估计值。质心的计算方法是:取N个点的横坐标和纵坐标的平均值,分别作为质心的横坐标和纵坐标。
以下是两个用于实现上述功能的C++类:
#include#include using namespace std;class Point {private: double x, y;public: Point(double a = 0, double b = 0) : x(a), y(b) { cout << setprecision(2) << fixed << "The Point (" << x << ", " << y << ") is created!\n"; } ~Point() { cout << setprecision(2) << fixed << "A Point (" << x << ", " << y << ") is erased!\n"; } Point(const Point &q) : x(q.x), y(q.y) { cout << setprecision(2) << fixed << "A Point (" << x << ", " << y << ") is copied!\n"; } double getX() { return x; } double getY() { return y; } double setX(double a) { x = a; } double setY(double b) { y = b; }};
#include#include using namespace std;class Graph {private: Point *points; int numOfPoints;public: Graph(Point *p, int n) : numOfPoints(n) { points = new Point[numOfPoints]; for (int i = 0; i < numOfPoints; ++i) { points[i] = p[i]; cout << "A graph with " << numOfPoints << " points is created!\n"; } } ~Graph() { delete[] points; cout << "A graph with " << numOfPoints << " points is erased!\n"; } Point *getCentroid() { double sumX = 0, sumY = 0; for (int i = 0; i < numOfPoints; ++i) { sumX += points[i].getX(); sumY += points[i].getY(); } double avgX = sumX / numOfPoints; double avgY = sumY / numOfPoints; return new Point(avgX, avgY); }};
int main() { int cases, num; double x, y; Point centroid; cin >> cases; for (int i = 0; i < cases; ++i) { cin >> num; Point *points[num]; for (int j = 0; j < num; ++j) { cin >> x >> y; points[j] = new Point(x, y); } Graph graph(points, num); centroid = graph.getCentroid(); cout << setprecision(2) << fixed << "The centroid is (" << centroid.getX() << ", " << centroid.getY() << ").\n"; } return 0;} Point类:
x和y,分别表示点的横坐标和纵坐标。x和y为0。x和y值,并打印创建信息。setX和setY方法,用于修改坐标值。getX和getY方法,用于获取坐标值。Graph类:
points,用于存储相邻点的集合。numOfPoints,用于存储相邻点的数量。points成员,并打印创建信息。getCentroid方法,计算质心。该方法遍历所有点,计算横坐标和纵坐标的总和,取平均值作为质心的坐标,并返回一个新的Point对象。主程序:
这个代码实现了对质心的计算和处理,满足用户的需求。每个Point对象在创建、复制和删除时都会打印相应的信息,确保程序的运行情况可追溯。
转载地址:http://oqxfk.baihongyu.com/