Loading...
Select Version
&pagelevel(4)&pagelevel
Definition | #include <stdlib.h> int rand(void);
A |
Return val. Note | Random number within [0, 215-1]. The random number generator can be initialized or reset with |
Example 1 | Generate the same five random numbers twice: #include <stdlib.h> #include <stdio.h> int i; int main(void) { for(i=1; i <= 10; ++i) { printf("%d\n", rand()); if(i == 5) srand(1); } return 0; } |
Example 2 | Simulation of rolling dice. #include <stdio.h> #include <stdlib.h> #define A 32767 /* 2**15 - 1 */ int cpu_t; /* Query variable for CPU time*/ int i,x; int main(void) { cpu_t = cputime(); srand(cpu_t); /* Seed value for the random generator */ for(i=1; i<= 6; ++i) /* Simulation of six throws of a die */ { x = rand()/(A/6)+1; /* Determine random number in range 1-6 */ printf("number thrown= %d\n",x); } return 0; } |
See also | rand, srand |