Roman said:
Hello,
can you recommend better way to generate random number within the range
[10..50]:
int x;
x = rand() / (RAND_MAX / 50 + 1);
if (x < 10) x = x + 10;
#include <stdlib.h>
int rand_range(int min, int max)
{
return rand() / (RAND_MAX + 1.0) * (max - min + 1) + min;
}
This function generates a pseudo-random number in the range of
[min..max] inclusive.
Here's an example of how to use it:
#include <stdio.h>
#include <time.h>
int main(void)
{
int i, j;
srand(time(NULL));
for(i = 0; i < 20; i++)
{
for(j = 0; j < 20; j++)
{
printf("%3d", rand_range(10, 50));
}
putchar('\n');
}
return 0;
}
The output for one example run:
47 28 29 48 20 11 15 48 45 13 49 12 15 38 39 31 40 19 23 29
47 43 35 11 40 20 45 41 49 21 19 18 38 46 18 17 37 11 30 41
18 14 48 39 25 25 20 37 17 17 49 42 39 37 14 12 23 48 28 25
32 40 49 45 12 48 41 14 47 26 29 36 40 12 18 20 21 28 49 21
38 30 14 32 14 19 17 11 40 17 45 40 40 17 28 49 21 16 42 15
31 21 31 48 15 27 26 21 20 33 15 28 11 35 10 39 32 37 24 44
15 11 12 42 33 20 14 48 39 50 30 17 20 34 25 46 17 37 26 44
27 40 42 24 14 50 37 36 23 22 22 26 40 46 15 20 47 24 32 22
11 13 15 13 21 38 37 25 47 39 10 34 49 26 13 31 47 16 27 12
45 28 49 48 47 24 41 50 28 34 41 43 43 30 45 50 14 16 42 50
28 45 24 28 50 10 21 22 13 31 49 41 37 50 25 41 29 50 34 42
26 10 43 25 49 43 33 28 24 16 10 48 48 17 50 31 26 16 27 15
12 32 32 24 37 45 27 31 28 34 11 50 27 15 47 38 35 32 46 36
21 49 22 49 13 23 24 39 34 50 38 41 36 32 29 19 16 17 39 20
25 17 38 25 48 34 50 19 45 49 11 22 12 10 21 38 30 12 16 41
23 24 43 50 33 27 17 50 41 20 20 11 41 19 33 33 30 33 23 22
19 31 27 35 22 23 42 21 29 10 37 18 16 39 36 23 30 10 26 38
22 23 37 33 50 43 49 37 25 45 29 37 10 26 38 12 28 42 14 36
28 44 18 18 29 50 20 12 26 39 30 12 45 25 44 32 40 33 45 28
20 21 38 17 17 30 12 19 38 30 19 47 21 14 44 42 19 30 11 35