我是一個完全新的節目和我通過這促使我做下面的教程練習運行的浮點值:如何繞行條件給定的用戶輸入值
提示用戶輸入她的身高以英寸計。如果她身高不到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 對不起,你就不能騎猛禽。你需要更多的英寸170000000000000028。
我怎樣才能讓我的「... 1.7000000000000028更多英寸」。輸出爲十進制值,舍入爲小數點後一位,爲1.7?我需要它爲任何帶有小數的輸入值(例如51.5輸出「2.5英寸」等)工作?
可能的重複[如何在Java中將數字四捨五入爲小數點後n位](https://stackoverflow.com/questions/153724/how-to-round-a-number-to-n-decimal-places-在-JAVA) –