Geneate Random Value
//CREATE RANDOM NUMBER
//#include <time.h>
unsigned int iseed = (unsigned int)time(NULL); //Seed srand() using time() otherwise it will start from a default value of 1
srand (iseed);
#define RANDOM_MAX 11 //Random value from 0 - #
int random_value = (int)((1.0 + RANDOM_MAX) * rand() / ( RAND_MAX + 1.0 ) ); //Scale rand()'s return value against RAND_MAX using doubles instead of a pure modulus to have a more distributed result.
Note: RAND_MAX is not RANDOM_MAX
Example functions
//*********************************************
//*********************************************
//********** GENERATE RANDOM INTEGER **********
//*********************************************
//*********************************************
//MaxValue
// Random value will be from 0 to #
int GenerateRandomInt (int MaxValue)
{
unsigned int iseed = (unsigned int)time(NULL); //Seed srand() using time() otherwise it will start from a default value of 1
srand (iseed);
int random_value = (int)((1.0 + MaxValue) * rand() / ( RAND_MAX + 1.0 ) ); //Scale rand()'s return value against RAND_MAX using doubles instead of a pure modulus to have a more distributed result.
return(random_value);
}
USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.