定义Point类描述点的坐标,可以输出坐标,可以求两个点之间的距离。 主函数声明Point类数组Point p[5],输入5个点的坐标,根据5个点与原点[0,0]之间的距离,由近至远排序输出距离值。
时间: 2024-02-18 08:59:10 浏览: 27
好的,以下是 Point 类的定义和主函数实现的代码示例:
```cpp
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
class Point{
public:
Point(double _x = 0, double _y = 0):x(_x), y(_y){}
void print() const{
cout << "(" << x << ", " << y << ")";
}
double distance() const{
return sqrt(x * x + y * y);
}
friend bool operator<(const Point& p1, const Point& p2){
return p1.distance() < p2.distance();
}
private:
double x, y;
};
int main(){
Point p[5];
for(int i = 0; i < 5; i++){
double x, y;
cout << "请输入第" << i+1 << "个点的坐标:";
cin >> x >> y;
p[i] = Point(x, y);
}
sort(p, p+5); //按照距离排序
cout << "按照距离由近到远排序输出距离值:" << endl;
for(int i = 0; i < 5; i++){
p[i].print();
cout << " 距离原点的距离为:" << p[i].distance() << endl;
}
return 0;
}
```
在上面的代码中,我们定义了一个 Point 类,包含了点的坐标和输出坐标、求距离等功能。在主函数中,我们声明了一个 Point 类型的数组 p[5],并通过循环输入了 5 个点的坐标。接着,我们使用 sort 函数对这 5 个点按照距离进行排序,最后输出排序后的结果,即每个点到原点的距离。
相关推荐
![java](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)