# Answer to Question #458 in C++ for lily

Question #458

Write the statement(or statements) that uses function rand() to determine a random floating point number between 12.5 and 24.5 and assigns the number to variable ran1. How can I do this?

Expert's answer

You can do this next way:

1 #include "stdio.h"

2 #include <stdlib.h>

3 #include <time.h>

4

5 float randfloat() {

6 ....int i1 = rand(),

7 ........i2;

8 ....do {

9 ........i2 = rand();

10 ....} while (i2 < i1);

11 ....return i1*1./i2;

12 }

13 float randfloat(float from, float to) {

14 ....return from + (to-from)*randfloat();

15 }

16

17 int main() {

18 ....srand(time(NULL));

19 ....printf("%f %f %f\n", randfloat(12.5, 24.5), randfloat(12.5, 24.5), randfloa t(12.5, 24.5));

20 ....return 0;

21 }

1 #include "stdio.h"

2 #include <stdlib.h>

3 #include <time.h>

4

5 float randfloat() {

6 ....int i1 = rand(),

7 ........i2;

8 ....do {

9 ........i2 = rand();

10 ....} while (i2 < i1);

11 ....return i1*1./i2;

12 }

13 float randfloat(float from, float to) {

14 ....return from + (to-from)*randfloat();

15 }

16

17 int main() {

18 ....srand(time(NULL));

19 ....printf("%f %f %f\n", randfloat(12.5, 24.5), randfloat(12.5, 24.5), randfloa t(12.5, 24.5));

20 ....return 0;

21 }

Need a fast expert's response?

Submit orderand get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

## Comments

## Leave a comment