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
```


d) ```
(RAND_MAX-rand())/static_cast(RAND_MAX)*5 -2
```

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...

Answer the following statements true (T) or false (F)

1. Inside a Java method definition, you can use the keyword this as a name for the calling object. 2. Boolean expressions may be used to control if-else or while statements. 3. The modifier private means that an instance variable can be accessed by name outside of the class definition. 4. It is considered good programming practice to validate a value passed to a mutator method before setting the instance variable.

Computer Science & Information Technology

A ________ is a computer system that provides information to people in nontraditional places such as museums, grocery stores, or banks

A) tablet B) laptop C) podium D) kiosk

Computer Science & Information Technology

An environment in which you create and edit Visual Basic for Applications code and procedures is the ________

Fill in the blank(s) with correct word

Computer Science & Information Technology

If variable input data is needed, a _____ must be provided to explain what is needed.

A. dialog box B. list box C. menu bar D. toggle button

Computer Science & Information Technology