zoukankan      html  css  js  c++  java
  • C++面向对象类的实例题目十二

    题目描述:

    写一个程序计算正方体、球体和圆柱体的表面积和体积

    程序代码:

    #include<iostream>
    #define PAI 3.1415
    using namespace std;
    class Shape
    {
    	public:
    		virtual void ShapeName()=0;
    		virtual void area()
    		{
    			return ;
    		}
    		virtual void volume()
    		{
    			return ;
    		}
    };
    class Cube:public Shape
    {
    	public:
    		Cube(float len):length(len){};
    		void ShapeName()
    		{
    			cout<<"Cube:"<<endl;
    		}
    		void area()
    		{
    			double s = 6*length*length;
    			cout<<"Area:"<<s<<endl;
    		}
    		void volume()
    		{
    			double v = length*length*length;
    			cout<<"Volume:"<<v<<endl;
    		}
    	private:
    		float length;
    };
    class Sphere:public Shape
    {
    	public:
    		Sphere(float r):radius(r){};
    		void ShapeName()
    		{
    			cout<<"Sphere:"<<endl;
    		}
    		void area()
    		{
    			double s = 4*radius*radius*PAI;
    			cout<<"Area:"<<s<<endl;
    		}
    		void volume()
    		{
    			double v = (4*radius*radius*radius*PAI)/3;
    			cout<<"Volume:"<<v<<endl;
    		}
    	private:
    		float radius;
    };
    class Cylinder:public Shape
    {
    	public:
    		Cylinder(float r,float h):radius(r),length(h){};
    		void ShapeName()
    		{
    			cout<<"Cylinder:"<<endl;
    		}
    		void area()
    		{
    			double s = radius*radius*PAI + 2*PAI*radius*length;
    			cout<<"Area:"<<s<<endl;
    		}
    		void volume()
    		{
    			double v = radius*radius*PAI*length;
    			cout<<"Volume:"<<v<<endl;
    		}
    	private:
    		float radius;
    		float length;
    };
    int main()
    {
    	Shape * pt;
    	pt = new Cube(2);
    	pt->ShapeName();
    	pt->area();
    	pt->volume();
    	cout<<"==========================="<<endl;
    	pt = new Sphere(2);
    	pt->ShapeName();
    	pt->area();
    	pt->volume();
    	cout<<"==========================="<<endl;
    	pt = new Cylinder(2,2);
    	pt->ShapeName();
    	pt->area();
    	pt->volume();
    	cout<<"==========================="<<endl; 
    } 
    


    结果输出:

    Cube:
    Area:24
    Volume:8
    ===========================
    Sphere:
    Area:50.264
    Volume:33.5093
    ===========================
    Cylinder:
    Area:37.698
    Volume:25.132
    ===========================



  • 相关阅读:
    JavaScript中{}+{}
    网站性能优化
    C++是如何从代码到游戏的?
    C++是如何从代码到游戏的?
    【力扣】至少是其他数字两倍的最大数 中速题解
    代码编辑器选择Atom还是VScode?
    TIOBE 4 月榜单:少儿编程语言 Scratch 进入 TOP 20
    熟悉一下oncontextmenu事件的知识
    input属性type为file打开文件资源管理器时,如何限制多次选取或只能一次选取的行为
    HTML5的拖放事件
  • 原文地址:https://www.cnblogs.com/fuhaots2009/p/3503352.html
Copyright © 2011-2022 走看看