• 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. }

  • 相关阅读:
    KVM管理平台选型与开源企业级虚拟化平台oVirt详解
    java servlet 返回图片验证码
    WPF自定义Panel:让拖拽变得更简单
    如何创建自己的Spring Boot Starter并为其编写单元测试
    计算机底层原理
    网络安全深入学习第五课——热门框架漏洞(RCE— Apache Shiro 1.2.4反序列化漏洞)
    OJ题之反转链表
    React
    13个学习技巧,让你每天进步一点点
    数据分析:基于Pandas的全球自然灾害分析与可视化
  • 原文地址:https://blog.csdn.net/weixin_62264287/article/details/126136167