Machine-translated by Google. Questions are authored in English.
Top

Discussion

What will be the output of the program?

public class Listing17
{
    public static void main(String[] args)
    {
        long up = Math.round(2.5);
        long down = Math.round(-2.5);
        System.out.println(up + " " + down);
    }
}

  • A.The program prints 3 -2
  • B.The program prints 2 -2
  • C.The program prints 2 -3
  • D.The program prints 3 -3

Answer: A

Math.round adds one half and takes the floor, so a value exactly halfway always moves toward positive infinity. That sends 2.5 up to 3 and -2.5 up to -2. Expecting symmetry around zero is the trap; only the positive case matches the everyday rule.

No comment is present. Be the first to comment.
Loading…

Post your comment

Please log in or register to post a comment.