How to use the rand function to create numbers in a specific range?

I would like to make random numbers in a certain range, for example, "choose a random number from 18 to 35"? How can I do this using a function rand()?

+5
source share
4 answers

If it is written in C, then you are pretty close. Compilation of this code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    int i;
    for (i = 0; i < 1000000; i++) {
        printf("%d\n", rand()%(35-18+1)+18);
    }
}

And running it in the pipeline, you will get the following result:

chris@zack:~$ gcc -o test test.c
chris@zack:~$ ./test | sort | uniq -c
  55470 18
  55334 19
  55663 20
  55463 21
  55818 22
  55564 23
  55322 24
  55886 25
  55947 26
  55554 27
  55342 28
  55526 29
  55719 30
  55435 31
  55669 32
  55818 33
  55205 34
  55265 35

The key you forgot to add 1 is the fencepost error .

You can generalize this to a function:

int random_between(int min, int max) {
    return rand() % (max - min + 1) + min;
}
+6
source

, , - .

, , . , , 0..65536, Low..High, 18..35 .

:

 r = (rand() % (High - Low + 1)) + Low

rand() 0..65536. (High - Low + 1), (35 - 18 + 1 = 18). 0..17. Low (18), , r, 18..35. .

, , , , rand(). . - Bias. , , , rand(), (High - Low + 1). 3640 * 18 = 65520. rand() as :

  do forever {
     r = rand()
     if r <= 65520 then {
         r = (r % (High - Low + 1)) + Low
         break
         }
     } 

, rand().

+12
  • ?
  • ?
  • 18, 35 ?
  • ?

, rand() float [0.0... 1.0] (.. , 1.0, 1) -

hi = 36
lo = 18
res = int( (hi-lo)*rand() + lo ) # returns random values in 18..35

, hi - 1 (.. 18 35 , 36).

, .

0

, rand() 0 1.0

then use rand () * (35 - 18) + 18 to get a random number between 18 and 35.

Edit: for this you do not need mod.

-1
source

All Articles