题目:
代码:
#include <iostream>
#include <cmath>
using namespace std;
class Point_1D
{
protected:
float x;
public:
Point_1D()
{
x = 0;
}
void Set_1D()
{
cin >> x;
}
void distance(const Point_1D& p2)
{
float ret = fabs(p2.x - this->x);
cout << "Distance from Point " <<
x << " to Point " << p2.x << " is " <<
ret << endl;
}
};
class Point_2D : public Point_1D
{
protected:
float y;//2D平面上的y坐标
public:
Point_2D()
{
y = 0;
}
void Set_2D()
{
cin >> x >> y;
}
void distance(const Point_2D& p2)
{
float ret = sqrt((this->x - p2.x) * (this->x - p2.x) + (this->y - p2.y) * (this->y - p2.y));
cout << "Distance from Point(" <<
x << "," << y << ") to Point(" <<
p2.x << "," << p2.y <<
") is " << ret << endl;
}
};
class Point_3D : public Point_2D
{
protected:
float z;
public:
Point_3D()
{
z = 0;
}
void Set_3D()
{
cin >> x >> y >> z;
}
void distance(const Point_3D& p2)
{
float ret = sqrt((this->x - p2.x) * (this->x - p2.x) + (this->y - p2.y) * (this->y - p2.y) + (this->z - p2.z) * (this->z - p2.z));
cout << "Distance from Point(" <<
x << "," << y << "," <<
z << ") to Point(" <<
p2.x << "," << p2.y << "," <<
p2.z << ") is " << ret << endl;
}
};
int main()
{
int input;
do
{
cin >> input;
switch (input)
{
case 1:
{
Point_1D p1;
Point_1D p2;
p1.Set_1D();
p2.Set_1D();
p1.distance(p2);
}
break;
case 2:
{
Point_2D p3;
Point_2D p4;
p3.Set_2D();
p4.Set_2D();
p3.distance(p4);
}
break;
case 3:
{
Point_3D p5;
Point_3D p6;
p5.Set_3D();
p6.Set_3D();
p5.distance(p6);
}
break;
case 0:
break;
default:
break;
}
} while (input);
return 0;
}