我是编程的新手,并且正在执行一个教程练习,提示我执行以下操作:
提示用户输入以英寸为单位的身高。如果她的身高不足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英寸)外,它的运行效果非常好,由于浮点数,我的heightDiff输出为长十进制。
这是输入为52.3的输出:
输入以英寸为单位的身高:
52.3
抱歉,您不能乘坐猛禽。您还需要1.7000000000000028英寸。
如何获得我的“ ... 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(..)
还可以实现什么。