# 亂數 ## 引用函式庫 亂數的函式位於`stdio.h`函式庫中 ```cpp #include<stdio.h> ``` ## 使用方法 rand()會幫你隨機產生一個數字 範圍為 0~RAND_MAX ```cpp= #include<stdio.h> #include<stdlib.h> int main(){ int x=rand(); printf("%d",x); } ``` 輸出 ``` 41 ``` --- ## 有範圍限制的亂數 用`%`和`+`運算子控制範圍 取0~9的亂數 `rand()%10` 取0~99的亂數 `rand()%100` 取0~999的亂數 `rand()%1000` 取0~10的亂數 `rand()%11` 取0~100的亂數 `rand()%101` 取0~1000的亂數 `rand()%1001` 取1~10的亂數 `rand()%10+1` 取1~100的亂數 `rand()%100+1` 取1~1000的亂數 `rand()%1000+1` --- ## 解決每次輸出的亂數都一樣的問題 可以發現如果重複執行以下的程式碼,每次的輸出結果都會是一樣的。 ```cpp= #include<stdio.h> #include<stdlib.h> int main(){ for(int i=0;i<10;i++){ int x=rand()%100; printf("%d\n",x); } } ``` 執行第一次的輸出 ``` 41 67 34 0 69 24 78 58 62 64 ``` 執行第二次的輸出 ``` 41 67 34 0 69 24 78 58 62 64 ``` --- 這是因為rand()函式其實是利用一個公式去產出我們需要的亂數,會有一個數字使這個公式做運算,這個數字稱為seed,預設的seed是1,所以每次執行產出來的亂數都會一樣,因此我們要利用`srand()`函式設定seed的數使公式產生的數字都會不一樣,並且seed需要一個一直變化的數,最常使用的就是time(NULL); ```cpp srand(time(NULL)); ``` 並且time函示位於time.h函示庫中所以要引入它 ```cpp #include<time.h> ``` ## 最終結果 程式碼: ```cpp #include<stdio.h> #include<stdlib.h> #include<time.h> int main(){ srand(time(NULL)); for(int i=0;i<10;i++){ int x=rand()%100; printf("%d\n",x); } } ``` 執行第一次的輸出 ``` 38 98 82 40 47 80 47 1 25 69 ``` 執行第二次的輸出 ``` 64 49 56 38 27 26 79 51 46 53 ``` ###### tags: `中和高中`