Bad random number generation
May 11, 2014 at 8:27pm UTC
I'm trying to generate some random numbers using the rand function in the following member function. For some reason, it is giving all 0's for attack values, but then giving huge numbers like 312981231123 for the defense values. I know this is probably a stupid error located somewhere in the code, but I can't seem to find it. Can anyone help?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
void Character::dieRoll(Character attacker, Character defender)
{
srand (time(0));
// attacker
if (attacker.attackDieSides == 6)
{
attacker.die1 = rand() % 6 + 1;
attacker.die2 = rand() % 6 + 1;
attacker.die3 = rand() % 6 + 1;
if (attacker.attackDie == 3)
{
attack = attacker.die1 + attacker.die2 + attacker.die3;
}
else if (attacker.attackDie == 2)
{
attack = attacker.die1 + attacker.die2;
}
}
else if (attacker.attackDieSides == 10)
{
attacker.die1 = rand() % 10 + 1;
attacker.die2 = rand() % 10 + 1;
attack = attacker.die1 + attacker.die2;
}
// defender
defender.die1 = rand() % 6 + 1;
defender.die2 = rand() % 6 + 1;
defender.die3 = rand() % 6 + 1;
if (defender.defenseDie == 3)
{
defense = defender.die1 + defender.die2 + defender.die3;
}
else if (defender.defenseDie == 2)
{
defense = defender.die1 + defender.die2;
}
else if (defender.defenseDie == 1)
{
defense = defender.die1;
}
}
For reference, here is another member function of the same class that also uses random, but works just fine!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
void Character::startRoll()
{
srand (time(0));
cout << "Roll the die to see who attacks first!\n\n" ;
continuePlay();
playerStartRoll = rand() % 6 + 1;
enemyStartRoll = rand() % 6 + 1;
cout << "You rolled a " << playerStartRoll << endl
<< "The enemy rolled a " << enemyStartRoll << endl << endl;
continuePlay();
}
May 11, 2014 at 8:30pm UTC
srand should only be called once at the start of your program, dont call it each time you call your function.
May 11, 2014 at 10:17pm UTC
Thanks. I removed it from the functions and just placed it once in the main file. However, I'm still getting the same kind of numbers.
May 11, 2014 at 10:42pm UTC
The Character objects (attacker and defender) in dieRoll are copies of the Character objects that you passed to the function. If you want dieRoll to modify the objects that you passed to the function you can pass them by reference.
void Character::dieRoll(Character& attacker, Character& defender)
Note the extra &
Last edited on May 11, 2014 at 10:42pm UTC
Topic archived. No new replies allowed.