Re: [問題] 亂數程式連續執行

看板C_and_CPP作者 (非天夜翔)時間14年前 (2010/02/12 03:11), 編輯推噓0(000)
留言0則, 0人參與, 最新討論串6/6 (看更多)
※ 引述《justinC (無)》之銘言: : 遇到的問題: (題意請描述清楚) : 我的亂數程式在連續執行時, 由於時間間隔很短, : srand() 傳入的參數一樣,而造成兩次得到的亂數值相同, : 有人知道該如何將他打亂嗎? : update: 想到一個解法...加上 process pid 那如果說改以下面的方式: #include <process.h> #include <time.h> srand(time(NULL)*(unsigned int)getpid()); 這樣子的設法會不會比較好一些?? 因為要在極短的時間內出現同樣的pid的機會會比較少一些。 但是若沒有time這個因子, 又容易出現相同pid而造成沒有想要的亂數變化。 : 程式跑出來的錯誤結果: : >./a.out && ./a.out : i=1 : i=2 : i=6 : i=3 : i=2 : --- : i=1 : i=2 : i=6 : i=3 : i=2 : --- : 開發平台: (例: VC++ or gcc/g++ or Dev-C++, Windows or Linux) : Freebsd : 有問題的code: (請善用置底文標色功能) : #include <stdio.h> : #include <stdlib.h> : #include <time.h> : void f() : { : int iSecret; : iSecret = rand() % 10 + 1; : printf("i=%d\n",iSecret); : } : int main () : { : int iSecret;[A : srand (time(NULL) ); : int k=0; : for(k=0;k<5;k++){ : f(); : } : printf("---\n"); : return 0; : } : 補充說明: -- 希望消失到自由的風中, 渴望解除掉束縛的羈絆。 期望悄悄的消失在風中, 感受那沒有羈絆的自由。 -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 211.74.9.2
文章代碼(AID): #1BT5Px2c (C_and_CPP)
討論串 (同標題文章)
文章代碼(AID): #1BT5Px2c (C_and_CPP)