第四周项目1—三角形类雏形

本文介绍了使用C++实现三角形类的方法,包括输入三角形的三边长度、判断是否能构成三角形、计算周长及面积等功能。通过类的设计实现了良好的封装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >



#include <iostream>
#include"math.h"
using namespace std;
class triangle
{
   public:
     void setABC(double x,double y,double z);
     double perimeter();
     double area();
   private:
      double a,b,c;

};
int main()
{
    triangle tril;
    tril.setABC(4,5,6);
    cout<<"三角形的周长为:"<<tril.perimeter()<<'\t'<<"面积为:"<<tril.area()<<endl;
    return 0;
}

void triangle::setABC(double x,double y,double z)
{
    a=x;
    b=y;
    c=z;
}

double triangle::perimeter()
{
    int C;
    C=a+b+c;
    return  C;
}

double triangle::area()
{
    int p=(a+b+c)/2;
    int s;
    s=sqrt((p*(p-a)*(p-b)*(p-c)));
    return s;
}








运行结果:





#include <iostream>
#include "stdbool.h"
#include"math.h"
using namespace std;
class triangle
{
   public:
       void setA(double x)
       {a=x;}
       void setB(double y)
       {b=y;}
       void setC(double z)
       {c=z;}
       double getA()
       {return a;}
       double getB()
       {return b;}
       double getC()
       {return c;}

       bool istriangle();

       double perimeter()
       {
          return (a+b+c);
       }
       double area()
       {
           double s;
           double p;
           p=(a+b+c)/2;
           return sqrt((p*(p-a)*(p-b)*(p-c)));
       }
   private:
       double a,b,c;
};

bool triangle::istriangle()
{

    if(a+b>c&&a+c>b&&b+c>a)
        return true;
    else
        return false;

}
int main()
{
    triangle tril;
    double x,y,z;
    cout<<"请输入三角形三边";
    cin>>x>>y>>z;
    tril.setA(x);
    tril.setB(y);
    tril.setC(z);

    if(tril.istriangle())
    {
       cout<<"三条边为:"<<tril.getA()<<','<<tril.getB()<<','<<tril.getC()<<endl;
       cout<<"三角形的周长为:"<<tril.perimeter()<<'\t'<<"面积为:"<<tril.area()<<endl;
    }
    else
        cout<<"不能构成三角形"<<endl;

    return 0;
}


运行结果:







#include <iostream>
#include"math.h"
using namespace std;
class triangle
{
   public:
    triangle(double x,double y,double z);
    void showmessage()
    {
        cout<<a<<' '<<b<<' '<<c<<endl;
    }
   private:
       double a,b,c;

};
  triangle::triangle(double x,double y,double z)
{
    a=x;
    b=y;
    c=z;
}
int main()
{
    triangle tri(7,8,9);
    tri.showmessage();
    return 0;
}


运行结果



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值