Here are two functions I use for producing random integers:
int z(int minz,int maxz)
{
return (((rand( )*rand( ))+rand( ))%(max( 1, maxz-minz )+1))+minz;
}
void s()
{
srand( (unsigned)(time( 0 )+z( 0, 16384 )) );
}
Call z() with a minimum and maximum integer passed to it in order to retrieve a random integer in that range. For instance, let's say I did this:
for(int i=0;i<5;i++)
{
cout<
}
the program, upon reaching this loop, would output a vertical list of five integers from 1 to 6 inclusive. That is to say, each number in the list could be 1, 6, or any integer between 1 and 6. Of course, you don't have to output the integers, you can use them for other things as well. For instance, let's say you want something to happen with an 83% chance, you could do this:
if(z(1,100)<=83)
{
do_stuff_here();
}
You could also use them as array indices, or inputs for switch statements. You could cast them to other data types. And you could add and multiply them together to get biased ranges of numbers. The possibilities are nearly endless.
You may have noticed the s() function. It does not return anything. Its purpose is to reseed the random number generator. Strictly speaking, you don't need it. You could just use z() directly (in which case you should always get the same sequence of random numbers given the same input range), or you could seed the RNG manually. However, s() has been designed to maximize the level of randomness when reseeding multiple times very quickly one after the other. You should call s() once when the program first starts, and it can help to call it again before any large, repeated code blocks involving a lot of calls to z(), for instance a function intended to generate a complex data structure with random features.
Furthermore, z() is also more complex than it strictly needs to be. The additional complexity allows it to take wider ranges of numbers (although the function is still not perfect and it is advised not to use ranges larger than a few tens of thousands) and provide increased randomness, at the expense of some extra computational overhead. The versions of the functions shown here are designed for generators. You may want to use different versions for, say, real-time computer games.
You can also of course rename the functions if you like. I used very short names because I use these functions a lot (especially z()) and I don't want to type a long name every time. Be aware though that if you rename z() you will also have to change the call to z() inside s().