开发者

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

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

T开发者_JAVA技巧hank 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜