开发者

ranged random numbers in C [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

How to generate a random number from within a range - C

I'm looking for something I can use in C that will give me a random number between a and b. So something like rand(50) would give me a number between 1 and开发者_如何转开发 50.


From the comp.lang.c FAQ: How can I get random integers in a certain range?


You can use either rand or random to get an arbitrary random value, then you can take the result of that and mod it by the size of the range and then add the start offset to put it within the desired range. Ex:

(rand()%(b-a))+a


You need to use rand() and srand().

http://linux.die.net/man/3/rand

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜