1 / 7

隨機函數

隨機函數. 6-4.2 亂數函式. 所謂 亂數 ( Random number ),是由電腦自動產生一個數字 電腦的亂數其實是由一個 亂數產生器 產生的,函式名稱是 rand ,使用前記得將其表頭檔 <stdlib.h> 包含進來 格式:. 呼叫後會傳回 0~32767 之間的任意一數. 6-4.2  亂數函式. 例如:. 01 //Program name:06-04-02A.c 02 #include <stdio.h> 03 #include <stdlib.h> 04 int main() 05 { 06 int i;

miller
Download Presentation

隨機函數

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 隨機函數

  2. 6-4.2亂數函式 所謂亂數(Random number),是由電腦自動產生一個數字 電腦的亂數其實是由一個亂數產生器產生的,函式名稱是rand,使用前記得將其表頭檔<stdlib.h>包含進來 格式: 呼叫後會傳回0~32767之間的任意一數

  3. 6-4.2 亂數函式 例如: 01 //Program name:06-04-02A.c 02 #include <stdio.h> 03 #include <stdlib.h> 04 int main() 05 { 06 int i; 07 for (i=0;i<5;i++) 08 printf("%d\n",rand()); 09 system("PAUSE"); 10 return 0; 11 } 執行結果: 41 18467 6334 26500 19169

  4. 6-4.2 亂數函式 每次執行程式,產生亂碼的順序卻都相同,這是因為亂數產生器的「種子」(seed)並沒有改變,所產生的亂數都是屬於同一組 改變種子,就會產生另一組亂數 語法:

  5. 6-4.2 亂數函式 例如: 01 //Program name:06-04-02B.c 02 #include <stdio.h> 03 #include <stdlib.h> 04 int main() 05 { 06 int i; 07 srand(100); 08 for (i=0;i<5;i++) 09 printf("%d\n",rand()); 10 system("PAUSE"); 11 return 0; 12 } 執行結果: 365 1216 5415 16704 24504

  6. 6-4.2 亂數函式 改了亂數產生器的種子數,以後每次執行時,還是產生同樣的一組亂數 利用讀取系統時間的函式,產生一個種子數,讓亂數產生器每次執行都不一樣 時間函數表頭檔:time.h 使用方法如下: srand((unsigned)time(NULL));

  7. 6-4.2 亂數函式 例如: 01 //Program name:06-04-02C.c 02 #include <stdio.h> 03 #include <stdlib.h> 04 #include <time.h> 05 int main() 06 { 07 int i; 08 srand((unsigned)time(NULL)); 09 for (i=0;i<5;i++) 10 printf("%d\n",rand()); 11 system("PAUSE"); 12 return 0; 13 } 執行結果: 29921 18871 385 32432 808

More Related