1. 程式人生 > >5-3 兩點間距離計算

5-3 兩點間距離計算

2.x distance space 重載 生成 數據 使用 函數 結果

給出下面的一個基類框架:

class Point_1D

{ protected:

float x;//1D 點的x坐標

public:

Point_1D(float p = 0.0);

float distance(const Point_1D & p2);

}

以Point_1D為基類建立一個派生類Point_2D,增加一個保護數據成員:

float y;//2D平面上點的y坐標

以Point_2D為直接基類再建立一個派生類Point_3D,增加一個保護數據成員:

float z;//3D立體空間中點的z坐標

生成上述類並編寫主函數,根據輸入的點的基本信息,建立點對象,並能計算該點到原點的距離。

輸入格式: 測試輸入包含若幹測試用例,每個測試用例占一行(點的類型(1表示1D點,2表示2D點,3表示3D點) 第一個點坐標信息(與點的類型相關) 第二個點坐標信息(與點的類型相關))。當讀入0時輸入結束,相應的結果不要輸出。

輸入樣例:

1 -1 0

2 3 4 0 0

3 1 2 2 0 0 0

0

輸出樣例:

Distance from Point -1 to Point 0 is 1

Distance from Point(3,4) to Point(0,0) is 5

Distance from Point(3,3,3) to Point(0,0,0) is 3

參考代碼

#include<iostream>
#include
<math.h> using namespace std; //本題考察多層繼承,將數據設為保護類,並使用公有繼承 //建立一維類 class Point_1D { protected: float x;//1D 點的x坐標 public: void set_1D(){cin>>x;} float distance(const Point_1D & p2); }; //建立二維類 class Point_2D:public Point_1D { protected: float y;//2D平面上點的y坐標 public: void
set_2D(){set_1D();cin>>y;}//調用基類set方法 float distance(const Point_2D & p2); }; //建立三維類 class Point_3D:public Point_2D { protected: float z;//3D立體空間中點的z坐標 public: 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();a2.set_1D();a1.distance(a2);break; case 2:b1.set_2D();b2.set_2D();b1.distance(b2);break; case 3:c1.set_3D();c2.set_3D();c1.distance(c2);break; } cin>>type; } return 0; } //實現distance方法 &重載 float Point_1D::distance(const Point_1D & p2) { float a; a=fabs(x-p2.x); cout<<"Distance from Point "<<x<<" to Point "<<p2.x<<" 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 Point("<<p2.x<<","<<p2.y<<") 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 Point("<<p2.x<<","<<p2.y<<","<<p2.z<<") is "<<a<<endl; return a; }

歡迎指教,一起學習!

未經本人允許,請勿轉載!

謝謝!

5-3 兩點間距離計算