distance from point to origin (inherited)

Given a base class skeleton as follows:

class Point_1D

{ protected:

float x;//The x coordinate of the 1D point

public:

Point_1D(float p = 0.0);

float distance( );//Calculate the distance from the current point to the origin

}

Create a derived class Point_2D with Point_1D as the base class, and add a protected data member:

float y;//The y coordinate of the point on the 2D plane

Create a derived class Point_3D with Point_2D as the direct base class, and add a protected data member:

float z;//The z coordinate of the point in the 3D solid space

Generate the above class and write the main function, create a point object based on the basic information of the input point, and calculate the distance from the point to the origin.

Input format: Test input contains several test cases, each test case occupies one line (point type (1 means 1D point, 2 means 2D point, 3 means 3D point) The first point coordinate information (related to the type of point) Two point coordinate information (related to the type of point)). When 0 is read in, the input ends, and the corresponding result is not output.

Input sample:

1 -1

2 3 4

3 1 2 2

0

Sample output:

Distance from Point -1 to original point is 1

Distance from Point(3,4) to original point is 5

Distance from Point(1,2,2) to original point is 3

 

 

The implementation is as follows:

#include<iostream>
#include<math.h>
using namespace std;
class Point_1D
{
protected:
float x;//1D 点的x坐标
public:
//Point_1D(float p = 0.0);
void set_1D(){cin>>x;}
Point_1D(float a=0){x=a;}
float distance(const Point_1D & p2);
};
class Point_2D:public Point_1D
{
protected:
float y;//2D平面上点的y坐标
public:
Point_2D(float a=0,float b=0){x=a;y=b;}
void set_2D(){set_1D();cin>>y;}
float distance(const Point_2D & p2);
};
class Point_3D:public Point_2D
{
protected:
float z;//3D立体空间中点的z坐标
public:
Point_3D(float a=0,float b=0,float c=0){x=a;y=b;z=c;}
void set_3D(){set_2D();cin>>z;}
float distance(const Point_3D & p2);
};
int main()
{
int type;
Point_1D a1,a2;
Point_2D b1,b2;
Point_3D c1,c2;
cin>>type;
while(type)
{
switch(type)
{
case 1:a1.set_1D();a1.distance(a2);break;
case 2:b1.set_2D();b1.distance(b2);break;
case 3:c1.set_3D();c1.distance(c2);break;
}
cin>>type;
}
return 0;
}
float Point_1D::distance(const Point_1D & p2)
{
float a;
a=fabs(x-p2.x);
cout<<"Distance from Point "<<x<<" to original point is "<<a<<endl;
return a;
}
float Point_2D::distance(const Point_2D & p2)
{
float a;
a=sqrt((x-p2.x)*(x-p2.x)+(y-p2.y)*(y-p2.y));
cout<<"Distance from Point("<<x<<","<<y<<") to original point is "<<a<<endl;
return a;
}
float Point_3D::distance(const Point_3D & p2)
{
float a;
a=sqrt((x-p2.x)*(x-p2.x)+(y-p2.y)*(y-p2.y)+(z-p2.z)*(z-p2.z));
cout<<"Distance from Point("<<x<<","<<y<<","<<z<<") to original point is "<<a<<endl;
return a;
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324973942&siteId=291194637