【问题描述】
根据点的类构造线三角形类,并测试
【点的定义】
//根据点的定义,写出线段和三角形的定义,并通过主程序进行验证
//mypoint.h
class myPoint
{
public:
myPoint();
myPoint(double x, double y);
double getX();
double getY();
private:
double mX,mY;
};
【函数实现】
#include<iostream>
#include<cmath>
using namespace std;
myPoint::myPoint(double x, double y) {
mX = x;
mY = y;
}
myPoint::myPoint() {
mX = 0;
mY = 0;
}
double myPoint::getX() {
return mX;
}
double myPoint::getY() {
return mY;
}
class Line {
protected:
myPoint x;//定义2个点
myPoint y;
public:
Line(myPoint b, myPoint k) {
this->x = b;
this->y = k;
}
double GetDistance() {
double b;
b = sqrt((x.getX() - y.getX()) * (x.getX() - y.getX()) + ((x.getY() - y.getY()) * (x.getY() - y.getY())));
return b;
}
};
class Triangle {
protected:
myPoint x, y, z;
public:
Triangle(myPoint h, myPoint s, myPoint a) {
this->x = h;
this->y = s;
this->z = a;
}
double getGirth(){
Line a(x, y);//定义三条线段
Line b(y, z);
Line c(x, z);
double C;
C = a.GetDistance() + b.GetDistance() + c.GetDistance();//调用线类的函数
return C;
}
double getArea() {
//海伦公式=√[p(p-a)(p-b)(p-c)],计算三角形面积的函数
Line a(x, y);//定义三条线段
Line b(y, z);
Line c(x, z);
double p;
p = (this->getGirth()) / 2;
double f;
f = sqrt(p * (p - a.GetDistance()) * (p - b.GetDistance()) * (p - c.GetDistance()));//海伦公式计算三角形面积
return f;
}
};
【主函数】
int main() {
double x1, x2, x3, y1, y2, y3;
cout << "请输入点1的x的值:";
cin >> x1;
cout << "请输入点1的y的值:";
cin >> y1;
cout << "请输入点2的x的值:";
cin >> x2;
cout << "请输入点2的y的值:";
cin >> y2;
cout << "请输入点3的x的值:";
cin >> x3;
cout << "请输入点3的y的值:";
cin >> y3;
cout << "点1的坐标为:(" << x1 << "," << y1 << ")" << endl;
cout << "点2的坐标为:(" << x2 << "," << y2 << ")" << endl;
cout << "点3的坐标为:(" << x3 << "," << y3 << ")" << endl;
myPoint p1(x1, y1), p2(x2, y2), p3(x3, y3);
Line line1(p1, p2);
cout << "线长度:" << line1.GetDistance() << endl;
Triangle t(p1, p2, p3);
cout << "该三角形的周长为:" << t.getGirth() << endl;
cout << "该三角形的面积为:" << t.getArea() << endl;
return 0;
}