Puzzle R10

Generate random doubles 0<=d<100 until one is within epsilon of 50.0

[M-15] Write a main() program that keeps generating random doubles in the range 0.0 <= d < 100.0 until a random double is generated that is within a small value ε of 50.0. In other words, stop when a value d has been generated such that |d - 50.0| < ε. Example output is:

Target: 50.000000;  Epsilon: 0.010000
Closest value: 50.003052; occurred on trial: 2444

It would be wise to put an upper limit on the number of trials just in case you picked an ε that never can be reached. Hard-code the parameters of the program:

const int limit = 10000000 ;
const double MIN=0.0, MAX= 100.0;
const double TARGET=50.0;
const double EPSILON= 1.0e-2;


Previous Page        Answer         Next Page         Home