题目:定义一个基类Shape,在此基础上派生出Rectangle和Circle,二者都有getArea( )函数计算对象的面积,再使用Rectangle类创建一个派生类Square。在主函数中测试Rectangle、Circle和Square这三个类。
输入格式:
Rectangle的长和宽、Circle的半径、Square的边长
输出格式:
Rectangle、Circle和Square对应的面积。四舍五入到整数
输入样例 :
3 7 6 4
2.1 3.5 10.3 4.5
输出样例 :
21 113 16
7 333 20
#include <iostream>
#include<cmath>
using namespace std;
class Shape {
public:
double len, wid, rou, bi;
double getArea1(double len,double wid){ return len * wid;};//矩形算面积
double getArea2(double rou){ return 3.14*rou*rou;};//圆形算面积
double getArea3(double bi){return bi*bi;};//正方形算面积
};
class Rectangle :public Shape {
private:
double len, wid;
public:
Rectangle(double l, double w) :len(l), wid(w) {}
double getArea1() { return len * wid; }
};
class Circle :public Shape {
private:
double rou;
public:
Circle(double r) :rou(r) {}
double getArea2() { return 3.14 * rou * rou; }
};
class Square :public Shape {
private:
double bi;
public:
Square(double b) :bi(b) {}
double getArea3() { return bi * bi; }
};
int main()
{
double length, width, rough, bian;
while (cin >> length >> width >> rough >> bian) {
Shape* ps;
ps = new Rectangle(length, width);
Shape* pr;
pr = new Circle(rough);
Shape* pb;
pb = new Square(bian);
int a = round(ps->getArea1(length,width ));//利用数学库中的round函数可以对小数点后一位四舍五入
int b = round(pr->getArea2( rough));
int c = round(pb->getArea3(bian ));
cout << a << " " << b << " " << c << endl;
}
}
其中有个没有符合题目要求的地方不知道你发现了没有~