题目描述
编写一个程序,定义抽象基类Shape,在Shape类中定义虚函数area();由它派生出3个派生类:Circle(圆形)、Square(正方形)、Rectangle(矩形)。用虚函数分别计算几种图形面积。
1、要求输出结果保留两位小数。
2、要求用基类指针数组,使它每一个元素指向每一个派生类对象。
输入
测试数据的组数 t
第一组测试数据中圆的半径
第一组测测试数据中正方形的边长
第一组测试数据中矩形的长、宽
…
第 t 组测试数据中圆的半径
第 t 组测测试数据中正方形的边长
第 t 组测试数据中矩形的长、宽
输出
第一组数据中圆的面积
第一组数据中正方形的面积
第一组数据中矩形的面积
…
第 t 组数据中圆的面积
第 t 组数据中正方形的面积
第 t 组数据中矩形的面积
输入样例1
2
1.2
2.3
1.2 2.3
2.1
3.2
1.23 2.12
输出样例1
4.52
5.29
2.76
13.85
10.24
2.61
AC代码
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cmath>
using namespace std;
class Shape {
public:virtual double area() { return 0; }
};
class Circle:public Shape {
double radius;
public:
Circle(double r):radius(r){}
virtual double area() {
return radius * radius * 3.14;
}
};
class Square:public Shape {
double length;
public:
Square(double l) :length(l) {}
virtual double area() {
return length * length;
}
};
class Rectangle:public Shape {
double length, width;
public:
Rectangle(double l,double w) :length(l),width(w) {}
virtual double area() {
return length * width;
}
};
void print(Shape* p) {
cout << fixed << setprecision(2) << p->area() << endl;
}
int main()
{
Shape* p;
int t;
cin >> t;
double radius, width, length;
while (t--) {
cin >> radius;
Circle A(radius);
p = &A;
print(p);
cin >> length;
Square B(length);
p = &B;
print(p);
cin >> length >> width;
Rectangle C(length, width);
p = &C;
print(p);
}
}