C 庫 - srand() 函式



C 的stdlibsrand()函式用於初始化或設定'rand()'函式的種子,允許我們生成不同的隨機數序列。預設情況下,rand() 函式的種子值為 1。

語法

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

void srand(unsigned int seed)

引數

此函式接受單個引數:

  • seed − 一個無符號整數,表示種子值。

返回值

此函式不返回任何值。

示例 1

讓我們建立一個基本的 C 程式來演示srand()函式的使用。

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

int main() {
   // Set seed based on current time
   srand(time(NULL)); 
   int i;
   for (i = 0; i < 10; i++) {
      int value = rand();
      printf("%d ", value);
   }
   return 0;
}

輸出

以下是輸出結果,它總是顯示隨機數:

22673 30012 9907 5463 13311 32059 17185 6421 15090 23066

示例 2

以下是一個另一個示例,我們將生成特定範圍內的隨機數。使用srand()rand()函式。

#include <stdlib.h>
#include <stdio.h>
#include <time.h>
int main() {
   // Lower bound
   int lb = 20; 
   // Upper bound
   int ub = 100;
   
   // Initialize random seed based on current time
   srand(time(NULL)); 
   
   int i;
   for (i = 0; i < 5; i++) {
      // Generate a random number between lb and ub (inclusive)
      printf("%d ", (rand() % (ub - lb + 1)) + lb );
   }
   return 0;
}

輸出

以下是輸出結果,它總是顯示隨機數:

44 77 70 86 75
廣告
© . All rights reserved.