我是编程新手,正在完成教程练习,提示我执行以下操作:
提示用户输入她的高度(以英寸为单位)。如果她高度低于 54 英寸,请告知她无法骑乘猛禽以及她还需要多少英寸。如果她高度至少 54 英寸,请通知她可以骑猛禽。
我目前为此提示编写的代码如下
import java.util.Scanner;
public class Main {
public static void main(String [] args) {
Scanner scnr = new Scanner(System.in);
double userHeight = 0.0;
double heightDiff = 0.0;
System.out.println("Enter your height in inches: ");
userHeight = scnr.nextDouble();
heightDiff = 54 - userHeight;
if (userHeight >= 54.0) {
System.out.println(userHeight);
System.out.println("Great, you can ride the Raptor!");
}
else {
System.out.println(userHeight);
System.out.println("Sorry, you cannot ride the Raptor. You need " + heightDiff + " more inches.");
}
return;
}
}
当我运行该程序时,它工作得很好,除了当我使用涉及小数的输入时(例如 52.3 英寸),由于 float ,我的 heightDiff 输出是一个长小数。
这是输入为 52.3 时的输出:
Enter your height in inches: 52.3 Sorry, you cannot ride the Raptor. You need 1.7000000000000028 more inches.
如何才能获得“...1.7000000000000028 英寸”。输出为四舍五入到一位小数的十进制值并且为 1.7?我需要它适用于任何带小数的输入值(例如 51.5 输出“多 2.5 英寸”等)?
最佳答案
您可以像这样使用String.format("%.2f", heightDiff)
:
System.out.println("Sorry, you cannot ride the Raptor. You need " + String.format("%.2f", heightDiff )+ " more inches.");
String.format(..)
不会更改 heightDiff
。如果您尝试再次打印,heightDiff
仍将打印为 1.7000000000000028
。 String.format(..)
仅在打印 heightDiff
时格式化 heightDiff
的值>(通过System.out.println(..)
)。这就对了。
要了解有关 String.format(..)
的更多信息,请用 google 搜索,您会找到大量解释。您还可以了解使用 String.format(..)
还可以实现哪些功能。
关于java - 如何使用给定用户输入值的条件对浮点值进行舍入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44148235/