Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate pseudo random number between A to B (A,B are int)in GNU C just with standard library

Tags:

c

random

How to generate pseudo random number between A to B (A,B are int)in GNU C just with standard library

Thank you !

like image 905
Josh Morrison Avatar asked Jan 20 '23 22:01

Josh Morrison


2 Answers

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.

like image 86
Andrew White Avatar answered Jan 29 '23 19:01

Andrew White


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.

like image 45
Karl Knechtel Avatar answered Jan 29 '23 21:01

Karl Knechtel