前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Point_Array

Point_Array

作者头像
叶茂林
发布2023-07-30 11:19:47
1050
发布2023-07-30 11:19:47
举报

题目描述

上面是我们曾经练习过的一个习题,请在原来代码的基础上作以下修改:1、增加自写的拷贝构造函数;2、增加自写的析构函数;3、将getDisTo方法的参数修改为getDisTo(const Point &p);4、根据下面输出的内容修改相应的构造函数。

然后在主函数中根据用户输入的数目建立Point数组,求出数组内距离最大的两个点之间的距离值。

输入

测试数据的组数 t

第一组点的个数

第一个点的 x 坐标   y坐标

第二个点的 x坐标  y坐标

............

输出

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

...........

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

#include <iostream> #include <iomanip> //必须包含这个头文件 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.

思路分析

建立Point数组,求出数组内距离最大的两个点之间的距离值,我也没想到什么好的算法,只能两个for循环暴力找解了。

AC代码

代码语言:javascript
复制
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
class Point{
	double x,y;
	public:
		Point(){x=y=0;cout<<"Constructor."<<endl;}
		Point(double x,double y):x(x),y(y){cout<<"Constructor."<<endl;}
		Point(const Point &p){x=p.x;y=p.y;cout<<"Constructor."<<endl;}
		~Point(){cout<<"Distructor."<<endl;}
		double getX(){return x;}
		double getY(){return y;}
		void setXY(double x,double y){this->x=x;this->y=y;}
		void setX(double x){this->x=x;}
		void setY(double y){this->y=y;}
		double getDisTo(const Point & p){return sqrt((x-p.x)*(x-p.x)+(y-p.y)*(y-p.y));}
		
};
int main() {
	int t,x,y,n,i,j,maxi,maxj;
	double maxdistance=0;
	cin >> t;
	while (t--) {
		cin>>n;
		Point point[n];
		for(i=0;i<n;i++){
			cin>>x>>y;
			point[i].setXY(x,y);
		}
		for(i=0;i<n-1;i++)
		for(j=i+1;j<n;j++){
			if(point[i].getDisTo(point[j])>maxdistance){
				maxi=i;
				maxj=j;
				maxdistance=point[i].getDisTo(point[j]);
			}
		}
		cout<<"The longeset distance is "<<fixed<<setprecision(2)<<maxdistance<<",between p["<<maxi<<"] and p["<<maxj<<"]."<<endl;
	}
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2022-09-09,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 题目描述
  • 思路分析
  • AC代码
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档