【C++_OJ_类和对象】Point_Array(类+构造+对象数组)

本文介绍了如何使用C++编写代码来解决几何问题,通过定义Point类和计算两点间距离的方法,程序遍历给定点集,找出最长距离及其对应的点。涉及数据结构、面向对象编程和几何计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目描述

输入

测试数据的组数 t

第一组点的个数

第一个点的 x 坐标 y坐标

第二个点的 x坐标 y坐标

输出

输出第一组距离最大的两个点以及其距离

在C++中,输出指定精度的参考代码如下:

#include

#include //必须包含这个头文件

using namespace std;

void main( )

{ double a =3.141596;

cout<<fixed<<setprecision(3)<<a<<endl; //输出小数点后3位

输入样例1

2
4
0 0
5 0
5 5
2 10
3
-1 -8
0 9
5 0

输出样例1

Constructor.
Constructor.
Constructor.
Constructor.
The longeset distance is 10.44,between p[1] and p[3].
Distructor.
Distructor.
Distructor.
Distructor.
Constructor.
Constructor.
Constructor.
The longeset distance is 17.03,between p[0] and p[1].
Distructor.
Distructor.
Distructor.

#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;

class Point
{
private:
    double x, y;

public:
    Point() : x(0), y(0){};                                                                     //缺省构造函数
    Point(double x_val, double y_val) : x(x_val), y(y_val) { cout << "Constructor." << endl; }; //有参构造函数
    double getX() { return x; };
    double getY() { return y; };
    void setXY(double x_val, double y_val)
    {
        x = x_val;
        y = y_val;
    };
    void sexX(double x_val) { x = x_val; };
    void sexY(double y_val) { y = y_val; };
    double getDisTo(const Point &p); //计算当前点到参数点p的距离
    ~Point() { cout << "Distructor." << endl; };
};

double Point::getDisTo(const Point &p)
{

    return sqrt((x - p.x) * (x - p.x) + (y - p.y) * (y - p.y));
}

int main()
{
    int t;
    cin >> t;
    while (t--)
    {
        int n;
        cin >> n;
        int x, y, i, j;

        Point *p = (Point *)operator new[](n * sizeof(Point));
        for (int i = 0; i < n; i++)
        {
            cin >> x >> y;
            new (&p[i]) Point(x, y); // 有参构造函数构造
        }

        int max1 = 0, max2 = 0;
        double max = 0;
        for (i = 0; i < n; i++)
            for (j = 0; j < n; j++)
                if (p[i].getDisTo(p[j]) > max)
                {
                    max = p[i].getDisTo(p[j]);
                    max1 = i;
                    max2 = j;
                }

        cout << "The longeset distance is " << fixed << setprecision(2) << max;
        cout << ",between p[" << max1 << "] and p[" << max2 << "]." << endl;

        for (int i = 0; i < n; i++)
            p[i].~Point();  //析构对象
        operator delete(p); //释放空间
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ferry_xie

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值