美文网首页
(十一)Point

(十一)Point

作者: GoodTekken | 来源:发表于2023-03-28 22:41 被阅读0次
#include <iostream>
#include <cmath>

using namespace std;

class GPoint
{
    private:
        double x,y;
    
    public:
        void setX(double x)
        {
            this->x = x;
        }

        void setY(double y)
        {
            this->y = y;
        }

        double getX()
        {
            return this->x;
        }

        double getY()
        {
            return this->y;
        }
};

class ComputeDistance
{
    public:
        double distance(GPoint a, GPoint b)
        {
            return sqrt((a.getX() - b.getX())*(a.getX()-b.getX()) + (a.getY() - b.getY())*(a.getY()-b.getY()));
        }
};

int main()
{
    int i,j,numberOfPoints = 0;
    cout << "输入点的个数:";
    cin >> numberOfPoints;

    GPoint* points = new GPoint[numberOfPoints];  //创建保存点坐标的数组    //(1)
    memset(points, 0, sizeof(points));
    cout << "输入" << numberOfPoints << " 个点的坐标: ";
    for( i = 0; i < numberOfPoints; i++)
    {
        double  tmpx, tmpy;
        cin >> tmpx >> tmpy;
        points[i].setX(tmpx);
        points[i].setY(tmpy);
    }

    ComputeDistance* computeDistance = new ComputeDistance();  //(2)
    int p1 = 0, p2 = 1; //p1和p2用于表示距离最近的点对在数组中的下标
    double shortestDistance = computeDistance->distance(points[p1],points[p2]);

    //计算每一对点之间的距离
    for(i = 0; i < numberOfPoints; i++)
    {
        for(j = i + 1; j < numberOfPoints; j++)  //(3)
        {
            double tmpDistance = computeDistance->distance(points[i],points[j]);  //(4)

            if(tmpDistance < shortestDistance)  //(5)
            {
                p1 = i;
                p2 = j;
                shortestDistance = tmpDistance;
            }
        }
    }

    cout << "距离最近的点对是:(";
    cout << points[p1].getX() << ", " << points[p1].getY() << ") 和 (";
    cout << points[p2].getX() << ", " << points[p2].getY() << ")" <<endl;

    delete computeDistance;
    return 0;
}

答案:
(1)GPoint*

(2)ComputeDistance*

(3)numberOfPoints

(4)distance(points[i],points[j])

(5)tmpDistance < shortestDistance

相关文章

网友评论

      本文标题:(十一)Point

      本文链接:https://www.haomeiwen.com/subject/opdordtx.html