LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Random numbers aren't the size I want them (https://www.linuxquestions.org/questions/programming-9/random-numbers-arent-the-size-i-want-them-4175477954/)

errigour 09-20-2013 11:42 PM

Random numbers aren't the size I want them
 
I'm using the fuction below and I can't figure out when I used dice(6); why it produces numbers larger then 6. The function below that one is the function I am using and the results are under the code.

Code:

short int dice(int size)
{
    short int rc;

    rc = (rand() % (size - 1 + 1) + 1);
    return rc;
}

bool dice_attributes(struct players *ch)
{
    short int roll[4] = { 0, 0, 0, 0};

    roll[0] = dice(6);
    roll[1] = dice(6);
    roll[2] = dice(6);
    roll[3] = dice(6);
    ch->str += (roll[0] + roll[1] + roll[2] + roll[3]);
    roll[0] = dice(6);
    roll[1] = dice(6);
    roll[2] = dice(6);
    roll[3] = dice(6);
    ch->dex += (roll[0] + roll[1] + roll[2] + roll[3]);
    roll[0] = dice(6);
    roll[1] = dice(6);
    roll[2] = dice(6);
    roll[3] = dice(6);
    ch->con += (roll[0] + roll[1] + roll[2] + roll[3]);
    roll[0] = dice(6);
    roll[1] = dice(6);
    roll[2] = dice(6);
    roll[3] = dice(6);
    ch->in  += (roll[0] + roll[1] + roll[2] + roll[3]);
    roll[0] = dice(6);
    roll[1] = dice(6);
    roll[2] = dice(6);
    roll[3] = dice(6);
    ch->wis += (roll[0] + roll[1] + roll[2] + roll[3]);
    roll[0] = dice(6);
    roll[1] = dice(6);
    roll[2] = dice(6);
    roll[3] = dice(6);
    ch->cha += (roll[0] + roll[1] + roll[2] + roll[3]);
}

Strength : 25
Dexterity : 24
Charisma : 18
Intelligence : 25
Wisdom : 28
Constitution : 30

ntubski 09-20-2013 11:51 PM

You should use = instead of +=. Or else set the stats of ch to 0 before calling dice_attributes().

Also, the - 1 + 1 in dice is redundant.

astrogeek 09-20-2013 11:55 PM

Your size mod expression is probably not what you intend (size -1 +1), maybe a typo?

The value in ch is not necessarily zero, so explicitly set it to zero first, or better yet, use = instead of += in those lines.

Dang! ntubski was faster on the submit! ;)

errigour 09-20-2013 11:56 PM

Then I realize I was testing my back input and I kept adding things to my stats because of the += thanks very much!


All times are GMT -5. The time now is 11:46 PM.