1614 - 点的距离
创建一个CPoint 类,代表平面直角坐标系中的点,创建构造函数和运算符重载函数,运算符重载为类重载(非友元重载),可以实现计算两个点之间的距离。
要求:
1。输入两个点的坐标,输出两个点之间的距离
2。重载运算符为“-”
Input
输入第一行为样例数m,接下来m行每行4个整数分别表示两个点的横纵坐标。
Output
输出m行,通过重载“-”运算输出两点的距离,保留小数点后两位。
Examples
Input
1 0 0 2 0
Output
2.00
Solution C
#include<stdio.h> #include<math.h> int main() { int n,i; int x1,y1,x2,y2; double h; while (scanf("%d",&n)!=EOF){ for (i=1;i<=n;i++){ scanf("%d%d%d%d",&x1,&y1,&x2,&y2); h=sqrt( ( ( x1-x2 )*( x1-x2 ) ) + ( (y1-y2)*(y1-y2) ) ); printf("%.2f\n",h); if (i==n){ break; } } } return 0; }
Solution C++
#include <stdio.h> #include <math.h> class CPoint { int x,y; public: CPoint(int xx,int yy) { x=xx; y=yy; } double operator- (CPoint c); }; double CPoint::operator- (CPoint c) { return sqrt((x-c.x)*(x-c.x)+(y-c.y)*(y-c.y)); } int main() { //freopen("test.in", "r", stdin); //freopen("test.out", "w", stdout); int t; int ax, ay, bx, by; scanf("%d", &t); while (t--) { scanf("%d %d %d %d", &ax, &ay, &bx, &by); CPoint a(ax, ay), b(bx, by); printf("%.2f\n", a - b); } return 0; }