形状数组本关任务:编写一个能计算不同形状的面积数组的小程序。 相关知识 为了完成本关任务,你需要掌握:1.抽象类的定义,2.上转型的使用。 题目要求 写一个程序,定义抽象类Shape,由它派生出5个派生类:Circle(圆),Square(正方形),Rectangle(矩形),Trapezoid(梯形),Triangle(三角形),用虚函数area()分别计算几种图形的面积,并求他们的和,要求使用基类指针数组,使它的每个元素都指向一个派生类对象 编程要求 根据提示,在右侧编辑器补充代码。 测试说明 平台会对你编写的代码进行测试: 测试输入: 10 10 15 14 13 10 8 15 8 5 预期输出: `area sum=635.659 测试输入: 13 12 11 10 5 12 5 18 9 7 预期输出: area sum=854.409 #include <iostream> using namespace std; #include<string> #include"time.h" #include"math.h" #define PI 3.1415926; //请在begin和end之间填入代码 /**************begin*****************/ /****************end**************/ int main() { double r,h,e1,e2,e3,eup,ebo,w; cin>>r; Circle c(r); cin>>w; Square sq(w); cin>>e1>>e2>>e3; Triangle tr(e1,e2,e3); cin>>w>>h; Rectangle re(w,h); cin>>eup>>ebo>>h; Trapezoid trap(eup,ebo,h); double sum=0; /*****************begin*******************/ /******************end*****************/ cout<<"area sum="<<sum; }
时间: 2023-07-23 20:55:17 浏览: 153
#include <iostream>
#include <string>
#include <time.h>
#include <math.h>
#define PI 3.1415926;
using namespace std;
/**************begin*****************/
class Shape {
public:
virtual double area() = 0; //声明虚函数
};
class Circle :public Shape {
double r;
public:
Circle(double r) :r(r) {};
double area() { return PI * r * r; }
};
class Square :public Shape {
double w;
public:
Square(double w) :w(w) {};
double area() { return w * w; }
};
class Rectangle :public Shape {
double w, h;
public:
Rectangle(double w, double h) :w(w), h(h) {};
double area() { return w * h; }
};
class Trapezoid :public Shape {
double eup, ebo, h;
public:
Trapezoid(double eup, double ebo, double h) :eup(eup), ebo(ebo), h(h) {};
double area() { return ((eup + ebo) * h) / 2; }
};
class Triangle :public Shape {
double e1, e2, e3;
public:
Triangle(double e1, double e2, double e3) :e1(e1), e2(e2), e3(e3) {};
double area() {
double p = (e1 + e2 + e3) / 2;
return sqrt(p * (p - e1) * (p - e2) * (p - e3));
}
};
/****************end**************/
int main() {
double r, h, e1, e2, e3, eup, ebo, w;
cin >> r;
Circle c(r);
cin >> w;
Square sq(w);
cin >> e1 >> e2 >> e3;
Triangle tr(e1, e2, e3);
cin >> w >> h;
Rectangle re(w, h);
cin >> eup >> ebo >> h;
Trapezoid trap(eup, ebo, h);
double sum = 0;
/*****************begin******************/
Shape* shape[5]; //定义基类指针数组
shape[0] = &c;
shape[1] = &sq;
shape[2] = &tr;
shape[3] = &re;
shape[4] = &trap;
for (int i = 0; i < 5; i++) {
sum += shape[i]->area(); //调用虚函数
}
/******************end*****************/
cout << "area sum=" << sum;
}
阅读全文