题目描述
有一个名为Shape的基类,它有2个派生类:Circle(圆)和Rectangle(长方形)。测试程序如下:
int main() { double x,y,r,x2,y2; Shape *p; while (cin>>x>>y>>r) { p=new Circle(x,y,r); p->print(); cin>>x>>y>>x2>>y2; p=new Rectangle(x,y,x2,y2); p->print(); } }
要求:
(1)完成以下功能:对给出的圆心坐标与半径,求圆的周长; 对给出的长方形中心坐标和一个顶点坐标,求长方形的周长。
(2)设计3个类。在Shape中定义虚函数print,在 Circle和Rectangle中重载该函数计算并显示周长。
输入
包含多组测试例, 每组数据的第1行是圆心的坐标和半径,第2行是长方形的中心坐标和一个顶点坐标。
输出
圆的周长和长方形的周长(保留3位小数)。
样例输入 Copy
2 3.5 12.3 0 0 2.3 2.3 5 5 5.8 2 2 5.6 5.6
样例输出 Copy
77.244 18.400 36.424 28.800
代码: #include #include #include<math.h> using namespace std; #define IP 3.14; class Shape{ public: double c; virtual void print(){ cout<<fixed<<setprecision(3)<<c<<endl; } }; class Circle:public Shape { public: Circle(double x,double y,double r){ c=2rIP; } }; class Rectangle:public Shape { public: Rectangle(double x,double y,double x2,double y2){ c=(x-x2)4+4(y-y2); if(c<0) c=-c; } }; int main() { double x,y,r,x2,y2; Shape *p; while (cin>>x>>y>>r) { p=new Circle(x,y,r); p->print(); cin>>x>>y>>x2>>y2; p=new Rectangle(x,y,x2,y2); p->print(); } }