Latest web development tutorials

C 庫函數– rand()

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>

描述

C庫函數int rand(void)返回一個範圍在0到RAND_MAX之間的偽隨機數。

RAND_MAX 是一個常量,它的默認值在不同的實現中會有所不同,但是值至少是32767。

聲明

下面是rand() 函數的聲明。

int rand(void)

參數

  • NA

返回值

該函數返回一個範圍在0 到RAND_MAX 之間的整數值。

實例

下面的實例演示了rand() 函數的用法。

#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);
}

讓我們編譯並運行上面的程序,這將產生以下結果:

38
45
29
29
47

C 標準庫 - <stdlib.h> C標準庫- <stdlib.h>