2023.5.9编程一小时打卡

发布时间 2023-05-09 20:17:08作者: 信2211-8李欣垚

一、问题描述:

定义基类Point(点)和派生类Circle(圆),求圆的周长。Point类有两个私有的数据成员float x,y;Circle类新增一个私有的数据成员半径float r和一个公有的求周长的函数getCircumference();主函数已经给出,请编写Point和Circle类。

#include <iostream>
#include<iomanip>
using namespace std;
//请编写你的代码
int main()
{
    float x,y,r;
    cin>>x>>y>>r;
    Circle c(x,y,r);
    cout<<fixed<<setprecision(2)<<c.getCircumference()<<endl;
    return 0;
}
 

输入格式:

输入圆心和半径,x y r中间用空格分隔。

输出格式:

输出圆的周长,小数点后保留2位有效数字。

二、解题思路:

 首先定义一个点类和一个圆类,根据题目要求定义成员数据,然后定义其所需的构造函数包括有参构造函数和无参构造函数,再编写类的成员函数,在圆类中定义一个计算圆周长的成员函数,返回圆的周长,最后在主函数中,定义圆类的对象通过输入进行初始化,然后利用圆类的对象调用圆类的计算圆周长的成员函数,验证代码运行的可行性。

三、代码实现:

 1 #include <iostream>
 2 #include<iomanip>
 3 using namespace std;
 4 class Point
 5 {
 6 private:
 7     float x,y;
 8 public:
 9     Point(){}
10     Point(float a,float b):x(a),y(b)
11     {
12         cout<<"Point constructor called"<<endl;
13     }
14     ~Point()
15     {
16         cout<<"Point destructor called"<<endl;
17     }
18 };
19 class Circle:public Point
20 {
21 private:
22     float r;
23 public:
24     Circle(float a,float b,float c):Point(a,b)
25     {
26         r=c;
27         cout<<"Circle constructor called"<<endl;
28     }
29     ~Circle()
30     {
31         cout<<"Circle destructor called"<<endl;
32     }
33     double getCircumference();
34 };
35 double Circle::getCircumference()
36 {
37     return r*3.14*2;
38 }
39 int main()
40 {
41     float x,y,r;
42     cin>>x>>y>>r;
43     Circle c(x,y,r);
44     cout<<fixed<<setprecision(2)<<c.getCircumference()<<endl;
45     return 0;
46 }