Monday, April 1, 2013

Generating random numbers

A program showing the generation of random numbers with proper initialization using the system clock.

/* The random [rand()] function */
#include <stdio.h> #include <time.h> #include <stdlib.h> int main (void) { /* initialize random generator */ srand (time(NULL)); /* generate random numbers */ printf("RAND_MAX = %d\n", RAND_MAX); printf ("A number between 0 and RAND_MAX : %d\n", rand()); printf ("A number between 0 and 99: %d\n", rand() % 100); printf ("A number between 0 and 9: %d\n", rand() % 10); printf ("A number between 1 and 6: %d\n", (rand() % 6) + 1); return (0); }
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
RAND_MAX = 32767
A number between 0 and RAND_MAX : 10746
A number between 0 and 99: 43
A number between 0 and 9: 8
A number between 1 and 6: 2

No comments:

Post a Comment