Write function bmi that calculates body mass index (bmi = weight / height ^ 2).
if bmi <= 18.5 return “Underweight”
if bmi <= 25.0 return “Normal”
if bmi <= 30.0 return “Overweight”
if bmi > 30 return “Obese”
这道题目不难,主要的看点在于if else 的写法。
public static String bmi(double weight, double height) {
double args = weight / (height * height) ;
if (args <= 18.5) return "Underweight" ;
if (args <= 25.5 && args > 18.5) return "Normal";
if (args <= 30 && args > 25.5) return "Overweight";
if (args > 30) return "Obese"
return null;
}
@Test
public void testBMI() {
assertEquals("Normal", Calculate.bmi(80, 1.80));
}
这种写法是不算太好的,下面这种比较合适。
public static String bmi(double weight, double height) {
double args = weight / (height * height) ;
if (args > 30) return "Obese";
else if (args > 25.5) return "Overweight";
else if (args > 18.5) return "Normal";
else return "Underweight" ;
}
@Test
public void testBMI() {
assertEquals("Normal", Calculate.bmi(80, 1.80));
}
这种写法比较合理,else if 满足的条件是:不仅满足当前条件,还满足前一个条件的反条件。