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;
   
   /* 初始化隨機數發(fā)生器 */
   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>