-1
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int dorand(){
int i;
srand(time(0));
i = rand()%3+1;
return i;
}
int main(){
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}
問題是:四個printf打印的是相同的數字。 當我直接在主函數中執行rand()時,根本沒有任何問題,但是當我調用一個函數時,隨機生成會沉迷於相同的數字。請有人分享一些經驗嗎?rand()數字在C中功能上癮
我已經試過:
int main(){
srand(time(0)) //seeding in the main function before calling the dorand function
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
printf("\n %d \n", dorand());
return 0;
}
而且
int dorand(){
int i;
i = 0; //clearing the variable before attributing a new rand value
srand(time(0));
i = rand()%3+1;
return i;
}
很抱歉,如果我弄錯的東西,感謝幫助
您不斷重置種子。 –
儘量不要在每個函數調用中改變種子。嘗試調用這個'srand(time(0));'一次只在main(或其他地方)。 – jamesjaya
工作,感謝很多傢伙 –