Programming Reference/Librarys
Question & Answer
Q&A is closed
Generates a random Number
<time.h> is for this example nessesary
/* * rand example code * http://code-reference.com/c/stdlib.h/rand */ #include <stdio.h> #include <stdlib.h> #include <time.h> /* for srand salt */ int main ( void ) { int i; /* initialize random generator */ /* without srand, rand will generate only once random numbers */ srand ( time(NULL) ); /* comment it out to see what happend */ printf ("random number between 0 and 100: %d\n", rand() % 100); /* random number */ for(i=0; i<=5; i++){ printf("example %i, rand() = %d\n",i, rand()); } return 0; }
user@host:~/code-reference.com# ./rand random number between 0 and 100: 34 example 0, rand() = 1299618648 example 1, rand() = 556251950 example 2, rand() = 1934607721 example 3, rand() = 1297432736 example 4, rand() = 1147459184 example 5, rand() = 1432106816
<time.h> is for this example nessesary
This example will generate a random number between 2 given int numbers
/* * rand example code * http://code-reference.com/c/stdlib.h/rand */ #include <stdio.h> #include <stdlib.h> #include <time.h> int rand_between(int min, int max); int main( void ) { srand(time(NULL)); printf("rand between 5 - 42 : %d\n",rand_between(5,42)); printf("rand between 800 - 1000 : %d\n",rand_between(800,1000)); return 0; } int rand_between(int min,int max){ return(rand()%(max-min)+min); }
user@host:~/code-reference.com# ./rand rand between 5 - 42 : 36 rand between 800 - 1000 : 923