早教吧 育儿知识 作业答案 考试题库 百科 知识分享

C++编程:编写一个关于圆形的程序.模仿编程:classRectangle{private:intlength,width;public:Rectangle(){length=0;width=0;}Rectangle(inta,intb){length=a;width=b;}Rectangle(Rectangle&r){length=r.length;width=

题目详情
C++编程:编写一个关于圆形的程序.
模仿编程:
class Rectangle
{
private :
int length,width ;
public :
Rectangle()
{ length = 0; width = 0; }
Rectangle( int a,int b )
{ length = a; width = b; }
Rectangle( Rectangle &r )
{
length = r.length ; width = r.width ;
}
void Set( int a,int b )
{ length = a; width = b; }
……
} ;
void main()
{
Rectangle rect1 ;
rect1.Set( 5,10 ) ;
……
Rectangle rect2( 2*5,2*10 ) ;
……
Rectangle rect3( rect1 ) ;
……
}
编写一个关于圆形的程序.要求用C++类的方法定义一个圆的类,其中有:
①1个私有数据成员(半径)
②3个公有函数成员(设置半径、计算面积、计算周长)
③3个构造函数(分别为不带参数的构造函数、带1个参数的构造函数和1个拷贝构造函数)
主程序使用这个类来创建圆对象,要求:
①定义一个圆对象c1,从键盘输入一个值x并将其设定为c1的半径,计算并显示c1的面积和周长
②再定义一个圆对象c2,并将半径初始化为2x,计算并显示c2的面积和周长
③再定义一个圆对象c3,并用c1初始化c3,计算并显示c3的面积和周长
▼优质解答
答案和解析
#include 
using namespace std;
   
#define PI 3.141592635
  
class Circle
{
public:
    Circle() : _r(0.f){}
    Circle(double r) : _r(r){}
    Circle(const Circle& circle)
    {
        this->_r = circle._r;
    }

    void setRadius(double r)
    {
        this->_r = r; 
    }  

    double Area()
    {
        return PI * this->_r * this->_r; 
    }   

    double Circumference()
    {    
        return 2 * PI * this->_r; 
    }     
   
private:
    double _r;      
};  

int main()
{
    Circle c1;
    double x;
    cin >> x;
    c1.setRadius(x);
    cout << "c1面积:" << c1.Area() << endl;
    cout << "c1周长:" << c1.Circumference() << endl;

    Circle c2(2 * x); 
    cout << "c2面积:" << c2.Area() << endl;
    cout << "c2周长:" << c2.Circumference() << endl; 

    Circle c3(c1);  
    cout << "c3面积:" << c3.Area() << endl;
    cout << "c3周长:" << c3.Circumference() << endl;  
       
    return 0; 
}