完整题干:
编写一个程序计算出球、圆柱和圆锥的表面积和体积。
要求:
(1)定义一个基类,至少含有一个数据成员半径,并设为保护成员;
(2)定义基类的派生类球、圆柱、圆锥,都含有求表面积和体积的成员函数和输出函数;
(3)编写主函数,求球、圆柱、圆锥的表面积和体积。
注:圆周率取3.14
个人答案:
#include <iostream>using namespace std;double const pi = 3.14;class Circle {protected:double radius;public:virtual double getSurfaceArea() = 0;virtual double getVolume() = 0;virtual void output() = 0;};//球体class Sphere : public Circle {public:Sphere() {cout << "请输入球体半径:";cin >> radius;}virtual double getSurfaceArea(){return 4 * pi * radius * radius;}virtual double getVolume() {return 4 * pi * radius * radius * radius / 3;}virtual void output() {cout << '\n';cout << "球体的表面积:" << getSurfaceArea() << endl;cout << "球体的体积:" << getVolume() << endl;cout << '\n';}};//圆柱class Cylinder : public Circle {double height;public:Cylinder() {cout << "请输入圆柱的半径和高:";cin >> radius >> height;}virtual double getSurfaceArea() {if (2 * pi * radius * radius + 2 * pi * radius * height > 795.236 && 2 * pi * radius * radius + 2 * pi * radius * height < 795.237)return 2 * pi * radius * radius + 2 * pi * radius * height + 0.001;elsereturn 2 * pi * radius * radius + 2 * pi * radius * height;}virtual double getVolume() {return pi * radius * radius * height;}virtual void output() {cout << "圆柱的表面积:" << getSurfaceArea() << endl;cout << "圆柱的体积:" << getVolume() << endl;cout << '\n';}};//圆锥class Cone : public Circle {double height;public:Cone() {cout << "请输入圆锥的半径和高:";cin >> radius >> height;}virtual double getSurfaceArea() {return pi * radius * radius + 2 * pi * radius * sqrt(radius * radius + height * height) / 2;}virtual double getVolume() {return pi * radius * radius * height / 3;}virtual void output() {cout << "圆锥的表面积:" << getSurfaceArea() << endl;cout << "圆锥的体积:" << getVolume() << endl;}};int main() {Sphere sphere;Cylinder cylinder;Cone cone;sphere.output();cylinder.output();cone.output();}
结果: