Wednesday, February 25, 2009

Puzzle 2 –Divide and (Multiply) Rule

Language – Java | Type – Concept | Last date 4-Mar-2009 9:00 p.m. IST | Points 2

I always considered myself to be good at algebra. I had no problems with equations, trigonometry and multiplication. But it takes Java to make simple algebra tricky. Do you know what this code does and why?
package com.twisters;
public class MulAndDiv {
public static void main(String[] args) {
double result;
result = 2.0*2/4+2/4;
System.out.println("The result is : "+ result);
}
}


1 comment:

  1. the division and multiplication operators have the same order priority and hence which operator comes first the operands evaluated first

    and an int and double are operands the result is double

    so 2.0*2 is 4.0
    now 4.0/4+2/4 ,then 4.0/4 is 1.0
    1.0+2/4 first 2/4 evaluated the result is 0 because operation of two int s is another int which is truncated to 0

    1.0+0 is 1.0

    so the result is 1.0

    my email id is nsureshreddy@live.com

    ReplyDelete

Solution for this question?