写点类的定义,要求点类中提供求两点距离、根据三点求三角形面积的成员函数,并在main函数里进行测试、打印点的信息和计算结果。
时间: 2024-03-12 18:45:44 浏览: 36
好的,以下是点类的定义:
```cpp
#include <iostream>
#include <cmath>
class Point {
private:
double x;
double y;
public:
Point(double _x, double _y) : x(_x), y(_y) {}
double getX() const {
return x;
}
double getY() const {
return y;
}
double distanceTo(const Point& other) const {
double dx = x - other.x;
double dy = y - other.y;
return std::sqrt(dx * dx + dy * dy);
}
double areaWith(const Point& a, const Point& b) const {
double side1 = distanceTo(a);
double side2 = distanceTo(b);
double side3 = a.distanceTo(b);
double s = (side1 + side2 + side3) / 2;
return std::sqrt(s * (s - side1) * (s - side2) * (s - side3));
}
};
int main() {
Point p1(0, 0);
Point p2(3, 4);
Point p3(6, 0);
std::cout << "p1: (" << p1.getX() << ", " << p1.getY() << ")" << std::endl;
std::cout << "p2: (" << p2.getX() << ", " << p2.getY() << ")" << std::endl;
std::cout << "p3: (" << p3.getX() << ", " << p3.getY() << ")" << std::endl;
std::cout << "Distance between p1 and p2: " << p1.distanceTo(p2) << std::endl;
std::cout << "Distance between p2 and p3: " << p2.distanceTo(p3) << std::endl;
std::cout << "Distance between p3 and p1: " << p3.distanceTo(p1) << std::endl;
std::cout << "Area of triangle p1p2p3: " << p1.areaWith(p2, p3) << std::endl;
return 0;
}
```
在上面的代码中,我们定义了一个点类 Point,其中包含了 x 和 y 两个私有成员变量,以及求两点距离和根据三点求三角形面积的成员函数。在 main 函数中,我们创建了三个点 p1、p2 和 p3,并分别打印了它们的坐标和计算了它们之间的距离。最后,我们还计算了 p1、p2、p3 三个点组成的三角形的面积,并打印出来。
阅读全文