1614 - 点的距离

通过次数

0

提交次数

0

时间限制 : 1 秒 内存限制 : 32 MB

创建一个CPoint 类,代表平面直角坐标系中的点,创建构造函数和运算符重载函数,运算符重载为类重载(非友元重载),可以实现计算两个点之间的距离。

要求:

1。输入两个点的坐标,输出两个点之间的距离

2。重载运算符为“-

题目输入

输入第一行为样例数m,接下来m行每行4个整数分别表示两个点的横纵坐标。

题目输出

输出m行,通过重载“-”运算输出两点的距离,保留小数点后两位。

输入/输出样例

输入格式

1
0 0 2 0

输出格式

2.00

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;
}

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;
}

Java解答



import java.text.DecimalFormat;
import java.util.Scanner;

public class Main {
    private static Scanner s = new Scanner (System.in) ;
    private static DecimalFormat df = new DecimalFormat("0.00") ;
    public static void main(String[] args) {
		int n = s.nextInt() ;
		
		for (int i = 0; i < n; i++) {
			int x1 = s.nextInt() ;
			int y1 = s.nextInt() ;
			int x2 = s.nextInt() ;
			int y2 = s.nextInt() ;
			
			System.out.println(df.format(Math.sqrt((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2)))) ;
		}
	}
}