23、计算周长

问题描述 :

已定义一个Shape抽象类、常量PI以及main函数。
  请在Shape的基础上派生出矩形Rectangle和圆形Circle类,二者都有 GetPerim()函数计算并返回对象的周长。
  请编写这两个类的代码,使得在main函数中正确输出两个对象的周长。

提供的代码如下:
#include <iostream>
using namespace std;
const double PI=3.14;
class Shape
{
public:
    Shape() {}
    ~Shape() {}
    virtual float GetPerim()=0;
};
/*******在此编写代码********/
int main()
{
    Shape * sp;
    double r,width,height;
    cin>>r;
    sp=new Circle(r);
    cout<<sp->GetPerim ()<<endl;
    cin>>width>>height;
    sp=new Rectangle(width,height);
    cout<<sp->GetPerim()<<endl;
    return 0;
}

 

输入说明 :

 输入共两行,第一行输入一个半径,第二行输入矩形的宽和高,用空格进行分隔。

输出说明 :

 共输出两行,第一行输出圆的周长,第二行输出矩形的周长。

输入范例 :

10
6 4

输出范例 :

62.8
20

解题代码: 

#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<cstring>
#include<string>
#include<map>
#include<algorithm>
#include<set>
using namespace std;
#include <iostream>
using namespace std;
const double PI=3.14;
class Shape
{
public:
    Shape() {}
    ~Shape() {}
    virtual float GetPerim()=0;
};
/*******在此编写代码********/
class Rectangle: public Shape
{
private:
    double x,y;
public:
    Rectangle(double x1,double y1){x=x1,y=y1;};
float    GetPerim()
   {
      return 2.0*(x + y);
   }
};
class Circle: public Shape
{
private:
    double r;
public:
    Circle(double R){r=R;}
   float GetPerim()
   {
      return (2.0 * r*PI);
   }
};
int main()
{
    Shape * sp;
    double r,width,height;
    cin>>r;
    sp=new Circle(r);
    cout<<sp->GetPerim ()<<endl;
    cin>>width>>height;
    sp=new Rectangle(width,height);
    cout<<sp->GetPerim()<<endl;
    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值