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(RAND_MAX))*3 + 2
d. (RAND_MAX-rand())/static_cast(RAND_MAX)*5 -2
e. rand()/static_cast(RAND_MAX)*2 + 3

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(RAND_MAX)
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.

Computer Science & Information Technology

You might also like to view...

Press ________ to move the insertion point from one cell in a table to the next cell in the same row

A) [Shift]+[Tab] B) [Enter] C) [Tab] D) [Shift]+[Enter]

Computer Science & Information Technology

Select the true statement below.

a. Paying to be listed preferentially in a search engine is considered by many organizations to be a justified cost of doing business. b. Submit your site to search engines before it is finished. c. It only takes a few minutes to be listed in a search engine. d. All of the statements above are true.

Computer Science & Information Technology