三角形和正方形(C++)

这篇文章描述了一个编程问题,要求创建一个名为Polygon的基类,以及两个派生类Triangle和Square。Polygon类应包含长度和面积属性,以及比较面积的方法。Triangle和Square类需计算各自形状的面积。给定三角形和正方形的周长,程序应输出它们的周长、面积,并判断三角形的面积是否大于正方形的面积。
摘要由CSDN通过智能技术生成

【问题描述】

小羊用两根绳子分别围成了正三角形和正方形。现在小羊想知道两个多边形的面积,以及三角形是否比正方形更大。小羊虽然很可爱,但是数学不是他的长项,请你来帮帮他吧。

定义多边形基类Polygon类,及成员数据length和myArea,构造函数(参数为绳子长度,是整数)成员函数getLength(),getArea()。在Polygon类中重载运算符”>”,来比较两个多边形的面积大小。派生两个公有继承的派生类:Triangle类、Square类。


【输入形式】

分别输入三角形及正方形的绳长L1,L2(均为整数)。数据保证多边形面积均在double 范围内。

【输出形式】

输出五行,第一行是三角形的周长,第二行是三角形的面积,第三行是正方形的周长,第四行是正方形的面积,第五行是"Yes!"(如果三角形面积大于正方形面积)或者是"No!"(如果三角形面积不大于正方形面积)。

【样例输入】

12 12

【样例输出】

The length of the triangle is: 12

The area of the triangle is: 6.9282

The length of the square is: 12

The area of the square is: 9

No!

【示例代码】

#include  <iostream>
#include  <cmath>

using namespace std;

class Polygon {
public:
    Polygon(int len) {
        length = len;
        myArea = 0;
    }

    int getLength() {
        return  length;
    }

    bool operator>(Polygon &p) {
        if (this->myArea > p.myArea) {
            return true;
        } else {
            return false;
        }
    }

    double getArea() {
        return myArea;
    }

protected:
    int length;
    double myArea;
};

class Triangle : public Polygon {
public:
    Triangle(int len = 0) : Polygon(len) {
        double myEdge = len / 3.0;
        myArea = myEdge * myEdge * sqrt(3.0) / 4.0;
    }
};

class Square : public Polygon {
public:
    Square(int len = 0) : Polygon(len) {
        double myEdge = len / 4.0;
        myArea = myEdge * myEdge;
    }
};

int main() {
    int tlen, slen;
    cin >> tlen >> slen;
    Triangle t(tlen);
    Square s(slen);
    cout << "The  length  of  the  triangle  is:  " << t.getLength() << endl;
    cout << "The  area  of  the  triangle  is:  " << t.getArea() << endl;
    cout << "The  length  of  the  square  is:  " << s.getLength() << endl;
    cout << "The  area  of  the  square  is:  " << s.getArea() << endl;
    bool bigger = (t > s);
    cout<< (bigger ? "Yes!" : "No!") <<endl;  //三目运算符
    return 0;
}

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

*OASIS*

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值