This shows you the differences between two versions of the page.
c:stdlib.h:rand [2013/01/22 22:02] |
c:stdlib.h:rand [2024/02/16 01:04] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | {{keywords>wiki library source code example reference}} | ||
+ | ====== rand ====== | ||
+ | |||
+ | <code c> | ||
+ | #include <stdlib.h> | ||
+ | int rand(void); | ||
+ | </code> | ||
+ | ===== Description ===== | ||
+ | Generates a random Number\\ | ||
+ | |||
+ | |||
+ | |||
+ | <time.h> is for this example nessesary | ||
+ | ===== rand C Sourcecode Example 1 ===== | ||
+ | <code c> | ||
+ | /* | ||
+ | * 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; | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | ==== output of rand example 1 ==== | ||
+ | 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 | ||
+ | ===== rand C Sourcecode Example 2 ===== | ||
+ | This example will generate a random number between 2 given int numbers\\ | ||
+ | <code c> | ||
+ | /* | ||
+ | * 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); | ||
+ | } | ||
+ | </code> | ||
+ | |||
+ | ==== output of rand example 2 ==== | ||
+ | user@host:~/code-reference.com# ./rand | ||
+ | rand between 5 - 42 : 36 | ||
+ | rand between 800 - 1000 : 923 | ||
+ | |||
+ | |||