- C 標準庫
- C 庫 - 首頁
- C 庫 - <assert.h>
- C 庫 - <complex.h>
- C 庫 - <ctype.h>
- C 庫 - <errno.h>
- C 庫 - <fenv.h>
- C 庫 - <float.h>
- C 庫 - <inttypes.h>
- C 庫 - <iso646.h>
- C 庫 - <limits.h>
- C 庫 - <locale.h>
- C 庫 - <math.h>
- C 庫 - <setjmp.h>
- C 庫 - <signal.h>
- C 庫 - <stdalign.h>
- C 庫 - <stdarg.h>
- C 庫 - <stdbool.h>
- C 庫 - <stddef.h>
- C 庫 - <stdio.h>
- C 庫 - <stdlib.h>
- C 庫 - <string.h>
- C 庫 - <tgmath.h>
- C 庫 - <time.h>
- C 庫 - <wctype.h>
- C 標準庫資源
- C 庫 - 快速指南
- C 庫 - 有用資源
- C 庫 - 討論
- C 程式設計資源
- C 程式設計 - 教程
- C - 有用資源
C 庫 - srand() 函式
C 的stdlib 庫srand()函式用於初始化或設定'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
廣告