求兩點之間距離(20 分)
定義一個Point類,有兩個數據成員:x和y, 分別代表x坐標和y坐標,並有若干成員函數。 定義一個函數Distance(), 用於求兩點之間的距離。
輸入格式:
輸入有兩行: 第一行是第一個點的x坐標和y坐標; 第二行是第二個點的x坐標和y坐標。
輸出格式:
輸出兩個點之間的距離,保留兩位小數。
輸入樣例:
0 9 3 -4
輸出樣例:
13.34
#include<iostream> #include<cmath> #include<stdio.h> using namespace std; class Point{ private: double x,y; public: Point(double x,double y) { this->x = x; this->y = y; } double Getx() { return x; } double Gety() { return y; } double Distance(const Point &p) //定義拷貝構造函數 { x -= p.x; y -= p.y; return sqrt(x*x+y*y); } void ShowPoint() { cout << "<" << Getx() << "," << Gety() << ">" << endl; } }; int main() { double x1,y1,x2,y2; double x; cin >> x1 >> y1 >> x2 >> y2; Point P1(x1,y1); Point P2(x2,y2); x=P1.Distance(P2); cout.precision(2); cout.setf(ios::fixed); cout << x << endl; return 0; }
