用C++编写一个程序,多组输入,每组两个二维坐标(x1,y1),(x2,y2),定义一个类计算两点之间的距离,先按(x,y)的格式输出两个点的坐标,再输出距离(保留两位小数))
时间: 2024-02-08 12:36:05 浏览: 122
以下是C++代码实现:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point
{
private:
double x, y;
public:
Point(double x, double y)
{
this->x = x;
this->y = y;
}
double distance(Point p)
{
double dx = x - p.x;
double dy = y - p.y;
return sqrt(dx * dx + dy * dy);
}
void print()
{
cout << "(" << x << ", " << y << ")";
}
};
int main()
{
int t;
cin >> t;
while (t--)
{
double x1, y1, x2, y2;
cin >> x1 >> y1 >> x2 >> y2;
Point p1(x1, y1);
Point p2(x2, y2);
p1.print();
cout << " ";
p2.print();
cout << " ";
printf("%.2lf\n", p1.distance(p2));
}
return 0;
}
```
其中,`Point`类表示一个二维坐标点,包含私有成员变量`x`和`y`,以及公有成员函数`distance`和`print`。`distance`函数计算当前点与另一个点`p`之间的距离,`print`函数按照(x, y)的格式输出当前点的坐标。
在`main`函数中,首先读入测试数据的组数`t`。然后,对于每组测试数据,读入两个点的坐标,分别构造`Point`对象。接着,按照(x, y)的格式输出两个点的坐标,再输出它们之间的距离(保留两位小数)。
注意,在输出距离时,使用`printf`函数来控制输出格式,可以保留指定的小数位数。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.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)
![zip](https://img-home.csdnimg.cn/images/20241231045053.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)