//mypoint.h class myPoint { public: myPoint(); myPoint(double x, double y); double getX(); double getY(); private: double mX,mY; };
时间: 2024-01-27 20:06:13 浏览: 140
实验2MyPoint类
好的,根据您给出的点类定义,我可以为您提供构造线三角形类的代码,如下所示:
```
#include <cmath>
#include "mypoint.h"
class myLine {
public:
myLine(myPoint p1, myPoint p2): mP1(p1), mP2(p2) {}
double getLength() {
double x1 = mP1.getX(), y1 = mP1.getY();
double x2 = mP2.getX(), y2 = mP2.getY();
return std::sqrt((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1));
}
private:
myPoint mP1, mP2;
};
class myTriangle {
public:
myTriangle(myPoint p1, myPoint p2, myPoint p3): mP1(p1), mP2(p2), mP3(p3) {}
void print() {
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() {
return mL1.getLength() + mL2.getLength() + mL3.getLength();
}
double getArea() {
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:
myPoint mP1, mP2, mP3;
myLine mL1{mP1, mP2}, mL2{mP2, mP3}, mL3{mP3, mP1};
};
```
您可以在主函数中使用该类进行测试,如下所示:
```
#include <iostream>
#include "mytriangle.h"
int main() {
myPoint p1(0, 0), p2(0, 1), p3(1, 0);
myTriangle tri(p1, p2, p3);
tri.print();
return 0;
}
```
样例输出:
```
三角形的三个顶点为:
A(0, 0)
B(0, 1)
C(1, 0)
三边长分别为:
AB = 1
BC = 1.41421
CA = 1.41421
三角形的周长为:3.41421
三角形的面积为:0.5
```
阅读全文