Re: [問題] 亂數程式連續執行
int t1= time(NULL);
int t2= t1;
// get next t1
while (t1 == t2) {
t1= time(NULL);
}
srand(t1);// 設定 種子數
// 丟棄 前面的300個 亂數
for (i=0;i<300;i++) {
rand();
}
// 正常使用,產生你所需要的 亂數
.
.
.
※ 引述《justinC (無)》之銘言:
: 遇到的問題: (題意請描述清楚)
: 我的亂數程式在連續執行時, 由於時間間隔很短,
: srand() 傳入的參數一樣,而造成兩次得到的亂數值相同,
: 有人知道該如何將他打亂嗎?
: update: 想到一個解法...加上 process 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: 118.231.103.169
討論串 (同標題文章)