C. 图形面积(虚函数与多态)

题目描述

编写一个程序,定义抽象基类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);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值