计算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);
}
}
共 (0) 个答案