Thursday, June 28, 2012

Generating Random Numbers in ANSI C

To generate random numbers in ANSI C, you will need to include the standard library header:
The ANSI C standard library provides functions for generating random integers. Before generating random numbers, you must make sure that you initialize the random number generator with a random seed. This random seed can be provided by using the current time. This means you will also need to use the ANSI C time operations library:
 time_t seconds;
 int randomNumber = 0;
 double realRandomNumber = 0.0;

 /*Returns the number of seconds since 1 January 1970*/
 /*Initializes the random number generator*/

 /*Generates a random integer between 0 and RAND_MAX*/
 randomNumber = rand();

 /*Generates a random integer between 0 and 255*/
 randomNumber = rand()%255;

 /*Generates a random integer between 127 and 255*/
 randomNumber = rand()%(255-127) + 127;

 /*Generates a random integer between -127 and -255*/
 randomNumber = - (rand()%(255-127) + 127);

 /*Generates a random integer between -127 and 255*/
 randomNumber = rand()%(255+127) - 127;

 /*Generates a random floating point number between 0.0 and 255.0*/
 realRandomNumber = (double)(rand()%2550)/10.0;

 /*Generates a random floating point number between 127.3 and 255.4*/
 realRandomNumber = (double)(rand()%(2554-1273) + 1273)/10.0;

 /*Generates a random floating point number between -127.3 and -255.4*/
 realRandomNumber = - ((double)(rand()%(2554-1273) + 1273)/10.0);

 /*Generates a random floating point number between -127.3 and 255.4*/
 realRandomNumber =  (double)(rand()%(2554+1273) - 1273)/10.0;
  • You can obtain real random numbers by transforming the floating point number into a integer (ex: 253.23 -> 25323) and after using int rand(), dividing the result with 10^n (where n represents the number of digits after the decimal point).
  • You can obtain negative numbers (either integer or real) by applying the same rules as for positive and multiplying the result with -1.

No comments:

Post a Comment

Got a question regarding something in the article? Leave me a comment and I will get back at you as soon as I can!

Related Posts Plugin for WordPress, Blogger...
Recommended Post Slide Out For Blogger