【问题标题】:Too many decimal points in Java programJava程序中的小数点太多
【发布时间】:2015-02-03 03:41:38
【问题描述】:

我最近开始了 Java 编程的第一个学期,但在作业上陷入了僵局。任务是请求用户输入矩形上的点。用户必须输入高度、宽度、左下 x 坐标和左下 y 坐标。我终于设法编写程序,并且编译没有错误。我的问题是,当我使用带小数的数字(即 -4.3、8.7 等)时,左上角 x 和右上角 x 坐标的小数点太多。

为什么只有这些点显示太多小数?我只需要一位小数(5.6、3.4 等)。

我将向您展示我的代码和输出。如果我的代码草率,我很抱歉。我对此很陌生:

    import java.util.Scanner;

公共类矩形点 {

public static void main(String[]args)

{


    Scanner input = new Scanner(System.in);

    System.out.print("Please enter bottom/left x coordinate: ");

    double xbottomleft = input.nextDouble();

    System.out.print("Please enter bottom/left y coordinate: ");

    double ybottomleft = input.nextDouble();

    System.out.print("Please enter width: ");

    double width = input.nextDouble();

    System.out.print("Please enter height: ");

    double height = input.nextDouble();


    System.out.println("Bottom Left: (" + xbottomleft + "," + ybottomleft + ")");

    double xbottomright = xbottomleft;
    double ybottomright = ybottomleft + width;
    double xtopleft = xbottomleft + height;
    double ytopleft = ybottomleft;
    double xtopright = xtopleft;
    double ytopright = ytopleft + width;

    System.out.println("Bottom Right: (" + xbottomright + "," + ybottomright + ")");
    System.out.println("Top Left: (" + xtopleft + "," + ytopleft + ")");
    System.out.println("Top Right: (" + xtopright + "," + ytopright + ")");




}

}

以下是使用随机选择的数字作为输入时输出显示的内容:

请输入下/左x坐标:-4.3 请输入下/左y坐标:3.5 请输入宽度:7.6 请输入身高:8.7 左下:(-4.3,3.5) 右下:(-4.3,11.1) 左上角:(4.3999999999999995,3.5) 右上角:(4.3999999999999995,11.1)

这两个坐标有什么问题?我研究了格式,但我不知道如何在我的代码中实现它,同时还打印文本,例如“右下:”、“左上:”等。

【问题讨论】:

标签: java formatting decimal


【解决方案1】:

您正在使用双打,这是出了名的不准确。由于并非所有值都可以用双精度表示,因此有时值是近似值,如您在此处看到的。如果您想要更准确的结果,请尝试使用定点表示而不是浮点表示。

【讨论】:

    【解决方案2】:

    这两个坐标有什么问题?

    真的没什么。不幸的是how floating point numbers work

    我研究了格式,但我不知道如何在我的代码中实现它同时打印文本

    你可以说

    System.out.format("Bottom Right: (%2.3f,%2.3f)%n", xbottomright, ybottomright);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多