rand() 預設使用固定種子,每次程式執行產生的隨機序列完全相同,導致「隨機數總是那幾個」。
srand() 設定種子在呼叫 rand() 前,加入 srand((unsigned)time(NULL)),以當前時間作為種子,每次執行結果即不同。
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main() {
int a[20], i;
int range, count;
printf("請輸入隨機數範圍: ");
scanf("%d", &range);
printf("請輸入隨機數個數: ");
scanf("%d", &count);
// 關鍵:設定隨機種子,僅需呼叫一次
srand((unsigned)time(NULL));
for (i = 0; i < count; i++) {
a[i] = 1 + rand() % range; // 產生 1~range 的隨機整數
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
srand() 只需在程式啟動時呼叫 一次,切勿放在迴圈內重複呼叫,否則若時間未更新會產生相同序列。<time.h> 以使用 time(NULL)。rand_s (Windows) 或 /dev/urandom (Linux) 等安全隨機源。加上這一行,你的隨機數就會真正「隨機」起來!