【问题描述】 根据点的类构造线三角形类,并测试 【输入形式】输入三角形的3个坐标点 【输出形式】三角形的3个坐标点、3边长及周长和面积 【样例输入】
时间: 2023-11-29 21:07:16 浏览: 95
已知三点坐标求三角形面积-Java算法
好的,根据您的要求,我可以为您提供一个完整的代码实现,如下所示:
```
#include <iostream>
#include <cmath>
class Point {
public:
Point(double x = 0, double y = 0): mX(x), mY(y) {}
double getX() const { return mX; }
double getY() const { return mY; }
private:
double mX, mY;
};
class Line {
public:
Line(const Point& p1, const Point& p2): mP1(p1), mP2(p2) {}
double getLength() const {
double dx = mP1.getX() - mP2.getX();
double dy = mP1.getY() - mP2.getY();
return std::sqrt(dx * dx + dy * dy);
}
private:
Point mP1, mP2;
};
class Triangle {
public:
Triangle(const Point& p1, const Point& p2, const Point& p3): mP1(p1), mP2(p2), mP3(p3), mL1(mP1, mP2), mL2(mP2, mP3), mL3(mP3, mP1) {}
void printInfo() const {
std::cout << "三角形的三个顶点为:" << std::endl;
std::cout << "A(" << mP1.getX() << ", " << mP1.getY() << ")" << std::endl;
std::cout << "B(" << mP2.getX() << ", " << mP2.getY() << ")" << std::endl;
std::cout << "C(" << mP3.getX() << ", " << mP3.getY() << ")" << std::endl;
std::cout << "三条边的长度分别为:" << std::endl;
std::cout << "AB = " << mL1.getLength() << std::endl;
std::cout << "BC = " << mL2.getLength() << std::endl;
std::cout << "CA = " << mL3.getLength() << std::endl;
std::cout << "三角形的周长为:" << getPerimeter() << std::endl;
std::cout << "三角形的面积为:" << getArea() << std::endl;
}
double getPerimeter() const {
return mL1.getLength() + mL2.getLength() + mL3.getLength();
}
double getArea() const {
double a = mL1.getLength(), b = mL2.getLength(), c = mL3.getLength();
double p = (a + b + c) / 2;
return std::sqrt(p * (p - a) * (p - b) * (p - c));
}
private:
Point mP1, mP2, mP3;
Line mL1, mL2, mL3;
};
int main() {
double x1, y1, x2, y2, x3, y3;
std::cout << "请输入三角形的三个顶点坐标:" << std::endl;
std::cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3;
Point p1(x1, y1), p2(x2, y2), p3(x3, y3);
Triangle tri(p1, p2, p3);
tri.printInfo();
return 0;
}
```
样例输入:
```
0 0 0 1 1 0
```
样例输出:
```
请输入三角形的三个顶点坐标:
三角形的三个顶点为:
A(0, 0)
B(0, 1)
C(1, 0)
三条边的长度分别为:
AB = 1
BC = 1.41421
CA = 1.41421
三角形的周长为:3.41421
三角形的面积为:0.5
```
阅读全文