天天看点

第五周项目:对象作为数据成员

代码:

#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; //两点之间的距离(一点是当前点——想到this了吗?另一点为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);
    float perimeter(void);//计算三角形的周长
    float area(void);//计算并返回三角形的面积
    bool isTriangle();//判断是否为三角形
    bool isRightTriangle(); //是否为直角三角形
    bool isIsoscelesTriangle(); //是否为等腰三角形
private:
    CPoint A,B,C; //三顶点
};

CPoint::CPoint(double xx,double yy)
{
    x=xx;
    y=yy;
}

double CPoint::Distance (CPoint p) const
{
    double d;
    return d=sqrt((p.x-x)*(p.x-x)+(p.y-y)*(p.y-y));
}

void CPoint::input()
{
    cin>>x>>y;
}

void CPoint::output()
{
    cout<<"("<<x<<","<<y<<")"<<endl;
}

void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)
{
    A=X;
    B=Y;
    C=Z;
}

float CTriangle::perimeter(void)
{
    float c;
    return c=A.Distance(B)+A.Distance(C)+B.Distance(C);
}

float CTriangle::area(void)
{
    float s,p;
    p=(A.Distance(B)+A.Distance(C)+B.Distance(C))/2;
    return s=sqrt(p*(p-A.Distance(B))*(p-A.Distance(C))*(p-B.Distance(C)));
}

bool CTriangle::isTriangle()
{
    double a=B.Distance(C),b=A.Distance(C),c=A.Distance(B);
    if(a+b>c&&a+c>b&&b+c>a)
        return true;
    else
        return false;
}

bool CTriangle::isRightTriangle()
{
    double a=B.Distance(C),b=A.Distance(C),c=A.Distance(B);
    if(a*a+b*b==c*c||b*b+c*c==a*a||a*a+c*c==b*b)
        return true;
    else
        return false;
}

bool CTriangle::isIsoscelesTriangle()
{
    double a=B.Distance(C),b=A.Distance(C),c=A.Distance(B);
    if(a==b||a==c||b==c)
        return true;
    else
        return false;
}

int main()
{
    CPoint p1,p2,p3;
    cout<<"请输入第一个点的坐标:";
    p1.input();
    cout<<"请输入第二个点的坐标:";
    p2.input();
    cout<<"请输入第三个点的坐标:";
    p3.input();
    CTriangle T(p1,p2,p3);
    if(T.isTriangle())
    {
        cout<<"这三个点可以构成三角形"<<endl;
        cout<<"该三角形的周长为:"<<T.perimeter()<<endl;
        cout<<"该三角形的面积为:"<<T.area()<<endl;
        if(T.isRightTriangle())
        {
            cout<<"该三角形是直角三角形"<<endl;
        }
        else
            cout<<"该三角形不是直角三角形"<<endl;
        if(T.isIsoscelesTriangle())
        {
            cout<<"该三角形是等腰三角形"<<endl;
        }
        else
            cout<<"该三角形不是等腰三角形"<<endl;
    }
    else
        cout<<"这三个点不能构成三角形"<<endl;
    return 0;
}
           

运行结果:

第五周项目:对象作为数据成员
第五周项目:对象作为数据成员
第五周项目:对象作为数据成员