How to generate a pseudo-random number between A and B (A, B - int) in GNU C with only the standard library

How to generate a pseudo-random number between A and B (A, B - int) in GNU C with only the standard library

Thank!

+3
source share
2 answers

Assuming A <B then how about this ...

srand((unsigned)time(NULL)); 
r = (rand()%(B-A)) + A;

According to the comments below, it is possible that BA is essentially larger than RAND_MAX. In this case, you need to be more careful.

+6
source

srand , rand. rand 0 RAND_MAX; . - , , . , 7 , rand() % 7, (0, 1, 2, 3, 4, 5, 6) - 7. ( 7.) , .

, srand , - main().

. .

+3

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


All Articles