(十一)Point

#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

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容