Puzzle R9

Out of N random doubles 0 <= d < 100 print the one closest to 50

[M-12] Use randomDoubleRange() to generate N random doubles in the range 0.0 <= d < 100.0. Print the value that is closest to 50.0. As N gets larger, the output should get closer and closer to 50.0, until finally 50 is reached, if that is possible. Our randomDoubleRange() has large gaps between the values it can generate, and not all output values are possible, even if they are whole numbers.

Example output, for N=1000 is:

Closest: 49.841309; difference: 0.158691

Example output, for N=10000 is:

Closest: 50.003052; difference: 0.003052

You will need the function

 double fabs(double x)

Which returns the absolute value of its argument. Repeat the experiment for values other than 50.0. Try 51.0, 15.0, and a few others.



Previous Page        Answer         Next Page         Home