Here's a question from the Programmer's Final Exam in the Simon Roberts "Complete Java2 Certification Study Guide"
What is the value of the following expression?
Math.round(Math.random() + 2.50001);
A. 2
B. 3
C. It is impossible to say.
I say "C" but the book says B ???
------------------------------------------------
I set up a program to
test this ... one of the random numbers I got was 0.9587593517384946
so I figure I could eventually come up with a number like 0.9999993517384946
so if I add 0.9999993517384946 + 2.50001
I get something like 3.50000035
---------------------------------------------
now the documentation for
public static long round(double a)
Returns the closest long to the argument. The result is rounded to an integer by adding 1/2, taking the floor of
the result, and casting the result to type long. In other words, the result is equal to the value of the expression:
(long)Math.floor(a + 0.5d)
so (long)Math.floor(3.50000035 + 0.5d)
== (long)Math.floor(3.50000035 + 0.5d)
== (long)Math.floor(4.00000035)
== 4.
floor - Returns: the largest (closest to positive infinity) floating-point value that is not greater than the argument and is
equal to a mathematical integer. [B] I'd say most of the time you will get 3 as the answer EXCEPT when the random(0 number is greater than .999999...
based on this possibility, how can we say other than "impossible to say" as the right choice?