0
下面是兩個函數:一個擲骰子,一個擲骰子統計。當你擲骰子時,每次都會給你一個隨機值,這很好。然而,在統計數據時,它似乎給了我所有6次迭代的相同隨機值。我認爲這可能是因爲它沒有在每次迭代後正確重置resultStat。C - rand()的工作結果,但是我獲得的數組數相同
下面是代碼:
int Roll_Dice(int number_of_dice, int number_of_faces)
{
int i;
int result = 0;
srand((unsigned) time(NULL));
for (i = 0; i < number_of_dice; i++)
{
result = (rand() % number_of_faces) + 1;
}
return (result);
}
int Roll_Stat(int number_of_dice, int use_highest)
{
int i, a, b;
int numberRolled[number_of_dice];
int resultStat = 0;
for (i = 0; i < number_of_dice; i++)
{
numberRolled[i] = Roll_Dice(number_of_dice, 6);
}
for (a = i + 1; a < number_of_dice; a++)
{
if (numberRolled[i] > numberRolled[a])
{
b = numberRolled[i];
numberRolled[i] = numberRolled[a];
numberRolled[a] = b;
}
}
for (i = use_highest; i >= (number_of_dice - use_highest); i--)
{
resultStat += numberRolled[i];
}
return (resultStat);
}
或者在項目開始時播種一次。 – immibis
真棒!感謝Michael的快速回復,我將srand放在我的main()中,並從Roll_Dice中取出,它的功能非常強大:) – Andrew