Which of the following code fragments gives a random double value between 2 and 5 inclusive? You can assume that the random number seed has been set and any needed definitions and initializations have been made.
a. 3.0*rand() + 2
b. 3.0*(RAND_MAX-rand())/RAND_MAX + 2
c. ((RAND_MAX-rand())/static_cast
d. (RAND_MAX-rand())/static_cast
e. rand()/static_cast
Only d) gives consistently correct, useful answers.
Explanation: Part a) The library function rand() returns an int, not a double, so this is not correct. Part b) is syntactically correct but rand() returns an int between 0 and RAND_MAX. On one compiler available to this writer RAND_MAX is 2,147,483,647 (the value of the largest possible int value, MAX_INT). In 3.0*(RAND_MAX-rand()) the subtraction is done then the multiplication. Integer overflow is assured on this system before the computation is complete. On another compiler, RAND_MAX is 32,767, so b) would work there. This solution is to be avoided. Part c): Divide and multiply associate left to right, so the expression
(RAND_MAX-rand())/static_cast
gives a double between 0.0 and 1.0 . Multiplying by 3 scales this to 0.0 to 3.0, adding 2 gives 2.0 to 5.0 as required, without overflow. Parts d) and e) are wrong: d) gives a random number between 2.0 and 7.0 . e) gives a random double between 3.0 and 5.0.
You might also like to view...
Which of the following refers to the versatile bus architecture widely used for connecting peripheral devices?
A. ?Random Access Memory Bus B. ?Register Bus C. ?Cache Memory Bus D. ?Universal Serial Bus
In the table pictured above, each column represents a:
A) field. B) record. C) primary key. D) table.
Wiles and Reyes identified four critical characteristics that an evidence storage facility must possess. Which of the following helps describe a good lockup?
a. Nobody except the investigator is allowed in or out once the evidence is secured. b. There can only be a single entrance to the storage room and it must be locked with both an electronic lock and a physical lock. c. Access to the storage facility is limited to authorized storage custodians. d. Video recording equipment must monitor the access door of the facility 24/7 and that recording equipment must not be available to anyone except authorized personnel.
The human body exhibits remarkable resilience. State three examples in which the body compensates for failure of single body parts.
What will be an ideal response?