请阅读下面的程序,请在空白处填写正确的代码,以求算两点之间的距离。 #include <iostream> using namespace std; class Point { public: Point(double a, double b){ x = a, y = b; } friend double dist(Point& d1, Point& d2); //友元函数 private: double x, y; }; double dist(Point& d1, Point& d2) { double s; double dx = d1.x - d2.x; double dy = d1.y - d2.y; ; return s; } int main( ) { Point p1(1.0, 2.0), p2(4.0, 6.0); double d; ; cout << "p1, p2 distance = " << d << endl; return 1; }
时间: 2024-03-23 08:39:05 浏览: 41
下面是空白处的正确代码:
```
s = sqrt(dx * dx + dy * dy);
```
将其添加到 `dist()` 函数中即可。`sqrt()` 函数需要 `#include <cmath>` 库。同时在 `main()` 函数中要调用 `dist()` 函数并将其返回值赋给变量 `d`:
```
d = dist(p1, p2);
```
完整代码如下:
```c++
#include <iostream>
#include <cmath>
using namespace std;
class Point {
public:
Point(double a, double b) {
x = a, y = b;
}
friend double dist(Point& d1, Point& d2);
private:
double x, y;
};
double dist(Point& d1, Point& d2) {
double s;
double dx = d1.x - d2.x;
double dy = d1.y - d2.y;
s = sqrt(dx * dx + dy * dy);
return s;
}
int main() {
Point p1(1.0, 2.0), p2(4.0, 6.0);
double d;
d = dist(p1, p2);
cout << "p1, p2 distance = " << d << endl;
return 1;
}
```
输出结果为:
```
p1, p2 distance = 5
```