Java,双重比较,if ((BMI) >= 18.5 || (BMI) <= 24.9) 条件为真,而BMI=25.77777777777778

Java,Double comparison , if ((BMI) >= 18.5 || (BMI) <= 24.9) , the condition is true while BMI=25.77777777777778

这只是一个简单的 Java 代码,但得到了错误的结果:

import java.util.Scanner;

public class BMI_Calculator {

    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.print("Enter your weight(kg):");
        double w = s.nextDouble();
        System.out.printf("\n%s", "Enter you height(cm):");
        double h = s.nextDouble();
        h = h / 100;

        double BMI = w / (h * h);

        String b;

        if (BMI < 18.5) {
            System.out.println("less than 18.5");
            b = "Underweight";
        } else if ((BMI) >= 18.5 || (BMI) <= 24.9) {
            System.out.println("between 18.5 and 24.9");
            b = "Normal";
        } else if (BMI >= 25 || BMI <= 29.9) {
            System.out.println("between 25 and 29.9");
            b = "Overweight";
        } else {
            System.out.println("greater than 30");
            b = "Obese";
        }

        System.out.println("Your BMI is:" + BMI + "(" + b + ")");

    }

}

这是输出

Enter your weight(kg):58

Enter you height(cm):150

between 18.5 and 24.9

Your BMI is:25.77777777777778(Normal)

我认为这可能与 double 变量的精度有关,我尝试了相同的代码将变量声明为 float 而不是 double 并得到了相同的结果,我真的不明白怎么会这样(25.7 < 24.9)?!怎么办?!

else if ((BMI) >= 18.5 || (BMI) <= 24.9)

或 (||) 需要是 (&&)。您想检查 BMI 是否在范围内。

(下一个 else if 也这样做。)