2017-09-14 100 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个字符,则在结尾添加一个零。

此方法也适用于用科学记数法表示的数字。