|
Random Number Between Two Integers |
|
|
|
Source: SaferCode - Posted by Anthony Pell
|
This is a topic that is quite easy and doesn’t need much explanation but still many people manage to mess it up. Not going into a hyperbole, I’ll get straight to the point. When asked, people can quickly tell you how to get a random number between 0 and b (b being any number below the maximum random number possible, which is defined as RAND_MAX by most C compilers).
Using the function “rand” provided by most C libraries, this is as simple as:
result = rand() % b;
Basically, given any random number, if you take its modulus with a, you will obviously get a number between 0 and a -1. This is all fine and dandy, so now someone asks you to generate a random number between a and b (a < b). This one is also really simple but few people fumble out still. Just think of it this way.
Read this full article at SaferCode
Only registered users can write comments. Please login or register. Powered by AkoComment! |