如何在给定用户输入值的情况下使用条件舍入浮点值

How to round a float value using a conditional given a user input value

我是编程新手,正在 运行 完成教程练习,提示我执行以下操作:

提示用户以英寸为单位输入她的身高。如果她的身高低于 54 英寸,请告知她不能骑 Raptor 以及她还需要多少英寸。如果她至少有 54 英寸高,通知她可以骑 Raptor。

我目前针对这个提示写的代码如下

    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 的输出:

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.7000000000000028String.format(..) 只会在您打印 heightDiff 格式化 heightDiff 的值(通过 System.out.println(..))。这就对了。

要了解更多关于 String.format(..)、google 的信息,您会找到很多解释。您还可以了解使用 String.format(..).

还可以实现什么