第三章第六题(健康应用:BMI)(Health application: BMI)

早过忘川 提交于 2020-02-05 03:48:24

*3.6(健康应用:BMI)修改程序清单3-4,让用户输入重量、英尺和英寸。例如一个人身高是5英尺10英寸,输入的英尺值就是5、英寸值为10。注意:1英尺=0.3048米。

下面是一个运行示例:
Enter weight in pounds:140
Enter feet:5
Enter inches:10
BMI is 20.087702275404553

*3.6(Health application: BMI) Revise Listing 3.4, ComputeAndInterpretBMI.java, to let the user enter weight, feet, and inches. For example, if a person is 5 feet and 10 inches, you will enter 5 for feet and 10 for inches.

Here is a sample run:
Enter weight in pounds:140
Enter feet:5
Enter inches:10
BMI is 20.087702275404553

下面是参考答案代码:

import java.util.*;

public class ComputeAndInterpretBMIQuestion6 {
	public static void main(String[] args) {
		Scanner input = new Scanner(System.in);

		// Prompt the user to enter weight in pounds
		System.out.print("Enter weight in pounds: ");
		double weight = input.nextDouble();
		
		// Prompt the user to enter feet
		System.out.print("Enter feet: ");
		double feet = input.nextDouble();
				
		// Prompt the user to enter inches
		System.out.print("Enter inches: ");
		double inches = input.nextDouble();

		final double KILOGRAMS_PER_POUND = 0.45359237; // Constant
		final double METERS_PER_INCH = 0.0254; // Constant

		// Compute BMI
		double weightInKilograms = weight * KILOGRAMS_PER_POUND;
		double heightInMeters = (feet * 12 + inches) * METERS_PER_INCH;
		double bmi = weightInKilograms / (heightInMeters * heightInMeters);

		// Display result
		System.out.println("BMI is " + bmi);
		if (bmi < 18.5)
			System.out.println("Underweight");
		else if (bmi < 25)
			System.out.println("Normal");
		else if (bmi < 25)
			System.out.println("Overweight");
		else
			System.out.println("Obese");
		
		input.close();
	}
}

运行效果:
在这里插入图片描述
注:编写程序要养成良好习惯
如:1.文件名要用英文,具体一点
2.注释要英文
3.变量命名要具体,不要抽象(如:a,b,c等等),形式要驼峰化
4.整体书写风格要统一(不要这里是驼峰,那里是下划线,这里的逻辑段落空三行,那里相同的逻辑段落空5行等等)

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!