【发布时间】: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)
这两个坐标有什么问题?我研究了格式,但我不知道如何在我的代码中实现它,同时还打印文本,例如“右下:”、“左上:”等。
【问题讨论】:
-
至于为什么会这样(这里没有“错”):stackoverflow.com/questions/177506/…
标签: java formatting decimal