• Point(类与构造) Java


    目录

    题目描述

    思路分析

    AC代码


    题目描述

    下面是一个平面上的点的类定义,请在类外实现它的所有方法,并生成点测试它。

    输入

    测试数据的组数 t

    第一组测试数据点p1的x坐标 第一组测试数据点p1的y坐标 第一组测试数据点p2的x坐标 第一组测试数据点p2的y坐标

    ..........

    输出

    输出p1到p2的距离

    在C++中,输出指定精度的参考代码如下:

    #include

    #include //必须包含这个头文件

    using namespace std;

    void main( )

    { double a =3.141596;

    cout<

    }

    输入样例1

    2
    1 2 3 4
    -1 0.5 -2 5

    输出样例1

    Distance of Point(1.00,2.00) to Point(3.00,4.00) is 2.83
    Distance of Point(-1.00,0.50) to Point(-2.00,5.00) is 4.61

    思路分析

    Java的this和C++的不同,Java没有指针这个玩意,C++里面访问本对象数据是this加上->的方式,而Java则是this加上下标点.的方式,这里要注意一下。

    还有就是Java除了普通数据类型,创建类对象都需要使用new来创建,不然无法访问类对象的方式属性。

    调用sqrt()函数需要Math包,Java调用函数都十分讲究,一定把包名类名路径讲清楚。

    AC代码

    1. import java.util.Scanner;
    2. import java.lang.Math;
    3. class Point{
    4. double x,y;
    5. public Point(){
    6. x=y=0;
    7. }
    8. public Point(double x,double y){
    9. this.x=x;
    10. this.y=y;
    11. }
    12. public double getX(){
    13. return x;
    14. }
    15. public double getY(){
    16. return y;
    17. }
    18. public void setX(double x){
    19. this.x=x;
    20. }
    21. public void setY(double y){
    22. this.y=y;
    23. }
    24. public double distanceToAnotherPoint(Point point){
    25. return Math.sqrt((point.x-x)*(point.x-x)+(point.y-y)*(point.y-y));
    26. }
    27. }
    28. public class Main {
    29. public static void main(String[] args) {
    30. Scanner scan=new Scanner(System.in);
    31. int t=scan.nextInt();
    32. Point p1=new Point(),p2=new Point();
    33. while(t-->0){
    34. double x= scan.nextDouble(),y=scan.nextDouble();
    35. p1.setX(x);
    36. p1.setY(y);
    37. double x2=scan.nextDouble(),y2=scan.nextDouble();
    38. p2.setX(x2);
    39. p2.setY(y2);
    40. System.out.printf("Distance of Point(%.2f,%.2f) to Point(%.2f,%.2f) is %.2f\n",p1.getX(),p1.getY(),p2.getX(),p2.getY(),p1.distanceToAnotherPoint(p2));
    41. }
    42. }
    43. }

  • 相关阅读:
    css 左右滚轮无缝衔接
    WIFI跟WLAN是一样的吗
    sql性能优化
    【AGC】云托管新建站点时间过长的问题排查方法
    【UVA 101】 区块世界 The Blocks Problem or【POJ No.1208】
    Fiori 应用通过 Adaptation Project 的增强方式分享
    3.10、以太网交换机的生成树协议 STP
    Applications of Artificial Intelligence and Machine learning in smart cities
    First, rewinding head to replay your work on top of it...
    Linux--vim
  • 原文地址:https://blog.csdn.net/weixin_62264287/article/details/126136167