修改下列代码使其输出小数点后两位#include <iostream> #include <cmath> #include <algorithm> using namespace std; class Point { public: double x, y; Point() {} Point(double _x, double _y) : x(_x), y(_y) {} void print() const { cout << "(" << x << ", " << y << ")"; } double distanceTo(const Point& p) const { double dx = x - p.x, dy = y - p.y; return sqrt(dx * dx + dy * dy); } }; bool cmp(const Point& p1, const Point& p2) { double dist1 = p1.distanceTo(Point(0, 0)); double dist2 = p2.distanceTo(Point(0, 0)); return dist1 < dist2; } int main() { Point p[5]; for (int i = 0; i < 5; ++i) { cin >> p[i].x >> p[i].y; } sort(p, p + 5, cmp); cout << "与原点的距离:\n"; for (int i = 0; i < 5; ++i) { cout << p[i].distanceTo(Point(0, 0)) << " "; } cout << endl; return 0; }
时间: 2024-01-15 11:03:33 浏览: 20
在输出距离的部分,可以使用流控制符来限定输出的小数位数。修改一下最后一个for循环,如下所示:
```c++
cout << fixed << setprecision(2) << p[i].distanceTo(Point(0, 0)) << " ";
```
其中,`fixed`表示要输出小数点后固定位数的小数,`setprecision(2)`表示要输出两位小数。