【任务4】设计一个三角形类,能够输入三角形的三个顶点,求出其面积、周长,并判断其是否为直角三角形和等腰三角形。
提示:(1)这个问题需要用到两个类,顶点类参照任务3中的CPoint类;(2)三角形类参考下面CTriangle类的声明;(3)充分利用CPoint类中已有的代码实现;(4)关于三条边的处理,可以增加三个私有属性,在初始化时求出来备用,也可以在需要时计算得到。
#include <iostream>
#include <Cmath>
using namespace std;
class CPoint
{
private:
double x; // 横坐标
double y; // 纵坐标
public:
CPoint(double xx=0,double yy=0);
double Distance(CPoint p) const; // 两点之间的距离(一点是当前点,另一点为参数p)
void input(); //以x,y 形式输入坐标点
void output(); //以(x,y) 形式输出坐标点
};
class CTriangle
{
public:
CTriangle(CPoint &X,CPoint &Y,CPoint &Z):A(X),B(Y),C(Z){} //给出三点的构造函数
void setTriangle(CPoint &X,CPoint &Y,CPoint &Z);
double perimeter(void);//计算三角形的周长
double area(void);//计算并返回三角形的面积
bool isRightTriangle(); //是否为直角三角形
bool isIsoscelesTriangle(); //是否为等腰三角形
private:
CPoint A,B,C; //三顶点
};
void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)
{
A = X;
B = Y;
C = Z;
}
//计算三角形的周长
double CTriangle::perimeter()
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
return a + b + c;
}
//计算并返回三角形的面积
double CTriangle::area(void)
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
double p = (a + b + c) / 2;
return sqrt ( p * ( p - a ) * ( p - b ) * ( p - c ) );
}
//是否为直角三角形
bool CTriangle::isRightTriangle()
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
if( abs(a * a + b * b - c * c < 1e-6) || abs(a * a + c * c - b * b < 1e-6) || abs(c * c + b * b - a * a < 1e-6) )
return true;
else
return false;
}
//是否为等腰三角
bool CTriangle::isIsoscelesTriangle()
{
double a = B.Distance(C), b = C.Distance(A), c = A.Distance(B);
if( abs(a - b < 1e-6) || abs(a - c < 1e-6) || abs( b - c < 1e-6) )
return true;
else
return false;
}
//两点间距离
CPoint::CPoint(double xx,double yy):x(xx),y(yy){}
double CPoint::Distance(CPoint p) const
{
return sqrt ( (p.x - x) * (p.x - x) + ( p.y - y ) * ( p.y - y ) ) ;
}
//输出
void CPoint::output()
{
cout << "(" << x << "," << y << ")" << endl;
}
void main(void)
{
CTriangle Tri1( CPoint(0,0),CPoint(1,1),CPoint(-1,1) );
cout << "该三角形周长:" << Tri1.perimeter() << "该三角形面积:" << Tri1.area() << endl;
cout << "该三角形" << (Tri1.isRightTriangle()? "是":"不是") << "直角三角形" << endl;
cout << "该三角形" << (Tri1.isIsoscelesTriangle()? "是":"不是" )<< "等腰三角形" << endl;
system("pause");
}
上机感言:两个类一起用,各有各的职责,很清晰,通过任务五的分开写能更加清楚~