This shows you the differences between two versions of the page.
c:stdlib.h:srand [2013/01/22 22:02] |
c:stdlib.h:srand [2024/02/16 01:04] (current) |
||
---|---|---|---|
Line 1: | Line 1: | ||
+ | {{keywords>wiki library source code example reference}} | ||
+ | ===== srand ===== | ||
+ | <code c> | ||
+ | #include <stdlib.h> | ||
+ | void srand(unsigned int seed); | ||
+ | </code> | ||
+ | ===== Description ===== | ||
+ | srand is used to initialize the random number generator.\\ | ||
+ | The use of date / time to initialize the generator \\ | ||
+ | means that the generated sequence of numbers "random" is.\\ | ||
+ | |||
+ | <time.h> is for this example nessesary | ||
+ | ===== srand C Sourcecode Example ===== | ||
+ | <code c> | ||
+ | /* | ||
+ | * srand exmple code | ||
+ | * http://code-reference.com/c/stdlib.h/srand | ||
+ | */ | ||
+ | #include <stdio.h> | ||
+ | #include <stdlib.h> | ||
+ | #include <time.h> /* for time to initialize srand */ | ||
+ | |||
+ | int main ( void ) | ||
+ | { | ||
+ | |||
+ | int i; | ||
+ | /* initialize random generator */ | ||
+ | srand ( (unsigned int) time(NULL) ); /* comment it out to see what happend */ | ||
+ | |||
+ | /* random number */ | ||
+ | for(i=0; i<=5; i++){ | ||
+ | printf("example %i, for srand = %d\n",i, rand()); | ||
+ | } | ||
+ | return 0; | ||
+ | } | ||
+ | |||
+ | |||
+ | </code> | ||
+ | |||
+ | ==== output of srand example ==== | ||
+ | user@host:~/code-reference.com# ./srand | ||
+ | example 0, for srand = 796883283 | ||
+ | example 1, for srand = 1140159597 | ||
+ | example 2, for srand = 137384045 | ||
+ | example 3, for srand = 1204700693 | ||
+ | example 4, for srand = 763425562 | ||
+ | example 5, for srand = 472690191 |