0

I am learning C and I am trying to get a random float number between 10 and 20. This is what I have so far:

  srand(time(NULL));
  float x = (float) rand() / (float) (RAND_MAX) * 10 + 20;
  printf("%f\n", x );

Whenever I run it only gives me a number that's something like so 20.103979. What am I doing wrong and how can I correct it?

Gia
  • 45
  • 1
  • 6
  • 3
    This will give you a range of `20` to `30`. Think what happens when `rand` is giving `0` and what happens when it gives `RAND_MAX`. Also you should be aware that you will get a very limited *subset* of possible values in the range. – Eugene Sh. Apr 15 '21 at 16:32
  • @EugeneSh. Why will it give me a limited range of values? How can I get to make it not give me a limited range of values? – Gia Apr 15 '21 at 16:38
  • 2
    Because `rand` can only generate `RAND_MAX+1` different values. Which is quite limited comparing to the continuum of real values in the range `[10,20]` :) – Eugene Sh. Apr 15 '21 at 16:40
  • 1
    Limited because the value of `RAND_MAX` might be as small as `32767`. With `float`, if `RAND_MAX` is `2147483647` (2^31 - 1), then you get a better distribution of the possible values; using `double`, there would be lots of possible values that would not be generated. – Jonathan Leffler Apr 15 '21 at 16:41
  • Thanks to everyone, your comments helped. – Gia Apr 15 '21 at 16:46

0 Answers0