How to generate pseudo random number between A to B (A,B are int)in GNU C just with standard library
Thank you !
Assuming A < B then what about this...
srand((unsigned)time(NULL));
r = (rand()%(B-A)) + A;
As per the comments below, it is possible that B-A is, in fact, greater than RAND_MAX. In this case you will have to be more careful.
You should seed the random number generator with srand
only once, and then obtain random numbers with rand
. The rand
function returns numbers from 0 up to some constant RAND_MAX
; you are responsible for mapping the results onto the desired range. The traditional way to do this is with the modulus operator, which gives the remainder that results from an integer division. So if you want 7 different results, for example, then you take rand() % 7
and the result will be one of (0, 1, 2, 3, 4, 5, 6) - the possible remainders when dividing by 7. (Note that there are 7 of these.) Then you add an offset to create the desired range of results, as in Andrew White's example.
The easiest way to ensure that srand
is called just once is to do it at or near the beginning of main().
For more information, see the documentation for these functions.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With