C stdlib srand() 函式
示例
顯示 10 個介於 1 和 100 之間的隨機數
// Initialize the randomizer using the current timestamp as a seed
// (The time() function is provided by the <time.h> header file)
srand(time(NULL));
// Generate random numbers
for (int i = 0; i < 10; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
自己動手試一試 »
定義和用法
srand()
函式使用種子初始化 rand()
函式。種子指定 rand()
函式將遵循哪個數字序列。這意味著相同的種子將始終產生相同的隨機數序列。
srand()
函式定義在 <stdlib.h>
標頭檔案中。
語法
srand(unsigned int seed);
引數值
引數 | 描述 |
---|---|
seed | 指定 rand() 函式將遵循哪個數字序列的數字。 |
更多示例
示例
顯示相同的隨機數序列兩次
// Initialize the randomizer with a fixed value
srand(10000);
// Generate 5 random numbers
for (int i = 0; i < 5; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
printf("\n");
// Initialize the randomizer with the same value
srand(10000);
// Generate 5 random numbers
for (int i = 0; i < 5; i++) {
int num = rand() % 100 + 1;
printf("%d ", num);
}
自己動手試一試 »