我正在實作一個生成 2 個亂數的基本程式。問題是第一個數字的結果看起來像是遵循某種模式,但第二個看起來仍然正確。
輸出:
6584 679
6587 1427
6591 9410
6594 156
7733 3032
7737 3780
這是我的代碼:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main(){
srand(time(NULL));
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
那么這里有什么問題以及如何解決它。
任何幫助,將不勝感激。
我正在使用 Windows 10 64 位,gcc 8.1.0。
uj5u.com熱心網友回復:
每次運行程式時,time(NULL) 值都充當相同的種子值。您的 CPU 每次都會生成類似的起始 NULL 時間的原因。要擺脫這種影響,您需要使用種子值,這樣即使您的計算機以相同的時間(NULL)值啟動,它也需要獲得與其他運行不同的種子。為此,您只需執行以下操作:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
int main(){
srand((unsigned)time(NULL) * (unsigned)getpid());
int a = rand()%10001, b= rand()%10001;
printf("%d %d", a,b);
return 0;
}
完全歸功于@pmg,感謝您提出改進解決方案的意見。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/434824.html
