【问题标题】:Point2D Double doesn't store a doublePoint2D Double 不存储双精度
【发布时间】:2018-09-19 17:24:09
【问题描述】:

所以我正在研究一个三角形类,我想使用 Point2D.Double 来存储高精度的点。

import java.awt.geom.Point2D.Double;

public class Triangle {

private Double pointOne = new Double();
private Double pointTwo = new Double();
private Double pointThree = new Double();
private final float PERCISION = 0.009f;

public Triangle(double x1, double y1, double x2, double y2, double x3, double y3)
{
    pointOne.x = x1;
    pointOne.y = y1;
    pointOne.setLocation(x2, y2);
    pointOne.setLocation(x3, y3);

}

public Double getPointOne() 
{
    return pointOne;
}

public Double getPointTwo() 
{
    return pointTwo;
}

public Double getPointThree() 
{
    return pointThree;
}

但是,当我在 main 中测试它并输入下面的代码时,它会打印出坐标,但精度非常低。我尝试使用浮点数,但总是以相同的结果结束。

    Triangle tri = new Triangle( 0.0000, 0.0000, 2.0008, 0.0000, 0.0000, 2.0000);

    System.out.println("Point 1 coordinates: (" + tri.getPointOne().getX() + ", " + tri.getPointOne().getY() + ")");
    System.out.println("Point 2 coordinates: (" + tri.getPointTwo().getX() + ", " + tri.getPointTwo().getY() + ")");
    System.out.println("Point 3 coordinates: (" + tri.getPointThree().getX() + ", " + tri.getPointThree().getY() + ")");

这是打印出来的,以备不时之需。

点 1 坐标:(0.0, 2.0)

点 2 坐标:(0.0, 0.0)

点 3 坐标:(0.0, 0.0)

理想情况下,这就是我希望它打印出来的内容。

点 1 坐标:(0.0000, 2.0008)

点 2 坐标:(0.0000, 0.0000)

点 3 坐标:(0.0000, 0.0000)

【问题讨论】:

  • 谷歌搜索“如何在 Java 中格式化数字”。 0.0 和 0.0000 是同一个数学数字。双存储。它不存储格式化数字的方法。
  • 另外,修正你的代码:你从不初始化pointTwo和pointThree,你初始化poinOne 3次。

标签: java floating-point double


【解决方案1】:

自定义十进制格式

https://docs.oracle.com/javase/tutorial/i18n/format/decimalFormat.html

编辑:我误读了您的问题!忘记我所说的关于原语的内容,但您可能需要执行一些格式化

【讨论】:

  • 好的,但是当我输入以下内容时我不明白:Double point = new Double();点.x = 0.0000;点.y = 2.0008; System.out.println(point.x); System.out.println(point.y);它打印出 2.0008 而不仅仅是 2.0,我不明白我的班级和只是输入它之间的区别,我很困惑为什么一个打印出来的结果与另一个不同。
  • @mrpk 在您的问题下阅读我的第二条评论。
猜你喜欢
  • 2015-06-05
  • 2011-05-16
  • 2016-08-17
  • 1970-01-01
  • 1970-01-01
  • 2011-08-05
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多