lundi 27 juillet 2015

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

This is just a simple Java code but gets a wrong result:

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 + ")");

    }

}

This is the output

Enter your weight(kg):58

Enter you height(cm):150

between 18.5 and 24.9

Your BMI is:25.77777777777778(Normal)

I thought it might be related to precision of double variable, I tried the same code declaring the variables as float instead of double and got the same result , I really don't understand how could such a thing happen (25.7 < 24.9)?! how?!

Aucun commentaire:

Enregistrer un commentaire