C 庫 - rand() 函式



C 的stdlib 庫的rand() 函式用於返回範圍在 0 到 RAND_MAX 之間的偽隨機數。

RAND_MAX 表示 rand() 函式可以返回的最大值,其預設值可能因 C 庫的實現而異。但它保證至少為 32767。

語法

以下是 rand() 函式的 C 庫語法:

int rand(void)

引數

此函式不接受任何引數。

返回值

此函式返回一個介於 0 到 RAND_MAX 之間的整數值。

示例 1

在本例中,我們建立一個基本的 C 程式來演示 rand() 函式的使用。

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

int main() {
   // store the random value
   int rand_value = rand();
   // display the random value
   printf("Random Value: %d\n", rand_value);
   return 0;
}

以下是輸出:

Random Value: 1804289383

示例 2

下面的 C 程式用於使用 rand() 函式在一定範圍內顯示隨機數。

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

int main() {
   // display the random value
   int i;
   for(i=1; i<=5; i++)
   {
      printf("%d ", rand());
   }
   return 0;
}

輸出

以下是輸出:

1804289383 846930886 1681692777 1714636915 1957747793 

示例 3

讓我們再建立一個示例,我們正在建立一個 C 程式來生成將是 10 的倍數的隨機數。

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

int main() {
   // display the random value
   int num = 10;
   int i;
   for(i=1; i<=6; i++)
   {
      printf("%d ", rand()%num);
   }
   return 0;
}

輸出

以下是輸出:

3 6 7 5 3 5
廣告