Skip to content
Advertisement

division in java programming

The same formula gives different answers to 2296 and 1500, when the expected answer in both cases is 100. Please explain this behavior. I’m quite surprised by this simple thing. Initially I thought this must be due to operator precedence but I cannot understand this.

program with 2296 :

public class testpercent {
    public static void main(String args[]) {
            System.out.println("first formula  ===>"+(2296 * 100 )/2296);
            System.out.println("alternate formula  =====>" + (2296/(2296/100)));
    }
}

output:

first formula ===>100
alternate formula =====>104

same program with 1500:

public class testpercent {
    public static void main(String args[]) {
            System.out.println("first formula for ===>"+(1500 * 100 )/1500);
            System.out.println("alternate formula for =====>" + (1500/(1500/100)));
    }

}

output:

first formula ===>100

alternate formula =====>100

Advertisement

Answer

Program with 2296 first does (2296/100) giving 22.96 and drops the remainder of 96. Then does 2296/22 giving 104.

Program with 1500 just does the same but has no remainder and ends up with the “correct” answer.

If you want to get the output right using the alternate formula try using data types like double or float.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement