第五周上机实践项目2——对象作为数据成员

问题及代码

/*
 * Copyright (c) 2015, 烟台大学计算机学院
 * All rights reserved.
 * 文件名称:test.cpp
 * 作    者:辛彬
 * 完成日期:2015 年 4 月 5 日
 * 版 本 号:v1.0
 *
 * 问题描述:设计一个三角形类。
 * 输入描述:平面坐标。
 * 程序输出:面积、周长,并判断其是否为直角三角形和等腰三角形。
 */
#include <iostream>
#include <cmath>
using namespace std;
class CPoint
{
private:
    double x;  // 横坐标
    double y;  // 纵坐标
public:
    double Distance1(CPoint p) const; //两点之间的距离(一点是当前点——想到this了吗?,另一点为p)
    double Distance0() const;          // 到原点(0,0)的距离
    void input();  //以x,y 形式输入坐标点
    void output(); //以(x,y) 形式输出坐标点
};
class CTriangle
{
public:
  void setTriangle(CPoint &X,CPoint &Y,CPoint &Z);//
  float perimeter(void);//计算三角形的周长
  float area(void);//计算并返回三角形的面积
  bool isRightTriangle(); //是否为直角三角形
  bool isIsoscelesTriangle(); //是否为等腰三角形
private:
  CPoint A,B,C; //三顶点
  double a,b,c;
};
double CPoint::Distance1(CPoint p) const
{
    double dx=x-p.x,dy=y-p.y;
    return sqrt(dx*dx+dy*dy);
}
double CPoint::Distance0() const
{
    return sqrt(x*x+y*y);
}
void CPoint::input()
{
    char e;
    double xx,yy;
    cin>>e>>xx>>e>>yy>>e;
    x=xx;
    y=yy;
}
void CTriangle::setTriangle(CPoint &X,CPoint &Y,CPoint &Z)
{
    A=X;
    B=Y;
    C=Z;
}
float CTriangle::perimeter()
{
    double a,b,c;
    a=A.Distance1(B);
    b=B.Distance1(C);
    c=C.Distance1(A);
    return a+b+c;
}
float CTriangle::area()
{
    double a,b,c;
    a=A.Distance1(B);
    b=B.Distance1(C);
    c=C.Distance1(A);
    double p=(a+b+c)/2;
    return sqrt(p*(p-a)*(p-b)*(p-c));
}
bool CTriangle::isRightTriangle()
{
    double t;
    if(a>b)
    {
        t=b;
        b=a;
        a=t;
    }
    if(b>c)
    {
        t=c;
        c=b;
        b=t;
    }
    if(a*a+b*b==c*c)
        return true;
    else return false;
}
bool CTriangle::isIsoscelesTriangle()
{
    if(a==b||a==c||b==c)
        return true;
    else return false;
}
int main()
{
    CPoint a1,a2,a3;
    cout<<"输入第一个点:";
    a1.input();
    cout<<"输入第二个点:";
    a2.input();
    cout<<"输入第三个点:";
    a3.input();
    CTriangle a;
    a.setTriangle(a1,a2,a3);
    cout<<"三角形的周长为:"<<a.perimeter()<<endl;
    cout<<"面积为:"<<a.area()<<endl;
    if(a.isRightTriangle())
        cout<<"此三角形为直角三角形"<<endl;
    if(a.isIsoscelesTriangle())
        cout<<"此三角形为等腰三角形";
    return 0;
}

运行结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值