2017-09-14 76 views
0

我正在編寫計算一個人的BMI的程序。這是我給予的任務:計算BMI以及如何防止向上舍入浮點(Java)

「身體質量指數(BMI)是衡量健康與體重的指標,可以通過以千克爲單位計算體重併除以身高的平方米來計算。該程序提示用戶輸入體重W以英寸爲單位,身高H以英寸輸入,並顯示BMI。請注意,一磅爲0.45359237公斤,一英寸爲0.0254米。

輸入:(1號線),以在50實數200 (第2行)實數在10至100

輸出:BMI值(浮點應該只被打印,直到第二小數點)

問題是,無論何時使用「System.out.printf(」%。2f \ n「,BMI)」「,輸出都被舍入,而不是切斷小數點的其餘部分。這是我的代碼:

import java.util.Scanner; 
public class Main 
{ 

    public static void main(String[] args) 
    { 
     Scanner input = new Scanner(System.in); 
     double weight = input.nextDouble(); 
     double height = input.nextDouble(); 

     double weightKG; 
     double heightM; 
     double heightMSquare; 
     double BMI; 

     final double kilogram = 0.45359237; 
     final double meter = 0.0254; 

     while ((weight > 200) || (weight < 50)) // Error catching code. 
     { 
      weight = input.nextDouble(); 
     } 
     while ((height > 100) || (height < 10)) 
     { 
      height = input.nextDouble(); 
     } 

     weightKG = weight * kilogram; // Convert pounds and inches to 
kilograms and meters. 
     heightM = height * meter; 

     heightMSquare = Math.pow(heightM, 2); // Compute square of height in 
meters. 

     BMI = weightKG/heightMSquare; // Calculate BMI by dividing weight 
by height. 

     System.out.printf("%.2f\n", BMI); 
    } 
} 

回答

1

這是我寫的一個方法,用正則表達式和字符串操作解決了這個問題。

private static String format2Dp(double x) { 
    String d = Double.toString(x); 
    Matcher m = Pattern.compile("\\.(\\d+)").matcher(d); 
    if (!m.find()) { 
     return d; 
    } 
    String decimalPart = m.group(1); 
    if (decimalPart.length() == 1) { 
     return d.replaceAll("\\.(\\d+)", "." + decimalPart + "0"); 
    } 
    return d.replaceAll("\\.(\\d+)", "." + decimalPart.substring(0, 2)); 
} 

我所做的是將double轉換爲一個字符串,從中提取小數部分並對小數部分進行子串處理。如果小數部分只有1個字符,則在結尾添加一個零。

此方法也適用於用科學記數法表示的數字。