下面是一个运行示例:
Enter weight in pounds:140
Enter height in feet5
Enter height in inches:10
BMI is 20.087702275404553
Normal
修改程序清单3-4
要点提示:嵌入if语句来编写程序,计算身体质量指数。
身体质量指数(BMI)是关于身体指标的健康测量。可以通过以千克为单位的体重除以以迷为单位的身高的平方,得到BMI的值。针对20岁及以上的人群,他们的BMI值得说明表如下所示:
BMI | 说明 |
BMI < 18.5 | 偏瘦 |
18.5 ≤ BMI < 25.0 | 正常 |
25.0 ≤ BMI < 30.0 | 超重 |
30.0 ≤ BMI | 过胖 |
编写程序,提示用户输入以英镑为单位的体重,以及以英寸为单位的身高,然后显示BMI。注意:一磅是0.45359237千克,而一英寸是0.0254米。
程序清单3-4
package Chapter_03; import java.util.Scanner; public class Code_04 { public static void main(String[] args) { Scanner input = new Scanner(System.in); System.out.print("Enter weight in pounds:"); double weight = input.nextDouble(); System.out.print("Enter height in inches:"); double height = input.nextDouble(); final double kilograms = 0.45359237; final double meters = 0.0254; double weightKilograms = weight * kilograms; double heightMeters = height * meters; double BMI = weightKilograms / (heightMeters * heightMeters); System.out.println("BMI is " + BMI); if(BMI < 18.5) System.out.println("Underweight"); else if(BMI < 25.0) System.out.println("Normal"); else if(BMI < 30.0) System.out.println("Overweight"); else System.out.println("Obese"); } }
调试运行
Enter weight in pounds:140 Enter height in inches:70 BMI is 20.087702275404553 Normal
本题3.6程序代码:
温馨提示:以英尺等于12英寸
package Chapter_03;
import java.util.Scanner;
public class Code_04 {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter weight in pounds:");
double weight = input.nextDouble();
System.out.print("Enter height in feet");
double feed = input.nextDouble();
System.out.print("Enter height in inches:");
double inches = input.nextDouble();
final double weightKilograms = 0.45359237 * weight;
final double heightMeters = 0.3048 * feed + 0.0254 *inches;
double BMI = weightKilograms / (heightMeters * heightMeters);
System.out.println("BMI is " + BMI);
if(BMI < 18.5)
System.out.println("Underweight");
else if(BMI < 25.0)
System.out.println("Normal");
else if(BMI < 30.0)
System.out.println("Overweight");
else
System.out.println("Obese");
}
}
调试运行
Enter weight in pounds:140 Enter height in feet5 Enter height in inches:10 BMI is 20.087702275404553 Normal