Choosing a random number between two points in C

I was wondering if it is possible to generate a random number between two limits in c. That is, my program is installed as follows:

function x { generate random number; } while(1) { function x; delay } 

so I want a random number to be generated every time the function is called, but the number should be between, for example, 100 and 800

I know that the function already done is called random and randmize in stdlib.h I just don’t know how to create upper and lower limits.

thanks

+4
source share
3 answers

First, remember to align the PRNG once and only once :

 srand(time(NULL)); 

Then this function should do what you want.
(slightly tested seems to work)

 int RandRange(int Min, int Max) { int diff = Max-Min; return (int) (((double)(diff+1)/RAND_MAX) * rand() + Min); } 

In your case, you need:

 x = RandRange(100, 800); /* x will be between 100 and 800, inclusive */ 

This uses floating point math, which can be slower than modulo (%) arithmetic, but will have a smaller offset.

+6
source

First get a random number from 0 to 1 ( R ). Then scale it to the desired range ( R* (right limit - left limit) ). Then add the minimum required value.

 int rand_between(int l, int r) { return (int)( (rand() / (RAND_MAX * 1.0f)) * (r - l) + l); } 
+3
source

Look at the module module.

 int r = rand(); r = (r % 700) + 100; 

700 is the difference in range.

0
source

Source: https://habr.com/ru/post/1399842/


All Articles