mardi 1 mars 2016

C - result from rand() working but I get the same number across array

Below are two functions: one to roll a dice, and one to roll stats. When you roll a dice it gives you a random value each time which is good. However when rolling a stat, it seems to give me the same random value for all 6 iterations. I think it might be because it isn't properly resetting resultStat after each iteration.

Here is the code:

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);
}




Aucun commentaire:

Enregistrer un commentaire