Latest web development tutorials

C library functions - rand ()

C standard library - <stdlib.h> C standard library - <stdlib.h>

description

C library functionsint rand (void) returns a range of 0 to pseudo-random number RAND_MAX.

RAND_MAX is a constant, its default value in different implementations will vary, but the value is at least 32767.

statement

Here is the rand () function's declaration.

int rand(void)

parameter

  • NA

return value

The function returns an integer value in the range between 0 to RAND_MAX of.

Examples

The following example demonstrates the rand () function is used.

#include <stdio.h>
#include <stdlib.h>

int main()
{
   int i, n;
   time_t t;
   
   n = 5;
   
   /* 初始化随机数发生器 */
   srand((unsigned) time(&t));

   /* 输出 0 到 49 之间的 5 个随机数 */
   for( i = 0 ; i < n ; i++ ) {
      printf("%d\n", rand() % 50);
   }
   
  return(0);
}

Let's compile and run the above program, which will result in the following:

38
45
29
29
47

C standard library - <stdlib.h> C standard library - <stdlib.h>