题目描述
有一个名为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
提示
#define PI 3.14
# include <iostream>
using namespace std;
# include <iomanip>
# include <cmath>
class Shape
{
public:
virtual void print() {}
Shape(double x_, double y_)
{
x = x_;
y = y_;
}
double getX()
{
return x;
}
double getY()
{
return y;
}
private:
double x, y;
};
class Circle :public Shape
{
public:
Circle(double x_, double y_, double r_):Shape(x_, y_), r(r_){}
void print()
{
cout << fixed << setprecision(3) << 2 * 3.14 * r << endl;
}
private:
double r;
};
class Rectangle :public Shape
{
public:
Rectangle(double x_, double y_, double x1_, double y1_):Shape(x_, y_), x1(x1_), y1(y1_){}
void print()
{
cout << fixed << setprecision(3) << 4 * (fabs(x1 - getX()) + fabs(y1 - getY())) << endl;
}
private:
double x1, y1;
};
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();
delete[] p;//原程序中没有
}
}