Bug in dice rolling
Now I am getting low values such as 3, 4, 4, 5, 3, 7, when it should be values such as 10, 16, 11 etc, as its out of 18.
You're getting low values because you have the braces in the wrong place in your rollDice() function body.
Here's a version that works properly:
and here's a version that does away with the array allocation and the second loop looking for smallest:
[edited by - SDickson on April 11, 2004 3:06:27 PM]
Here's a version that works properly:
int rollDice() { const int NUMBER_OF_SIDES = 6; // Summate 4 dice rolls int Roll[4]; int i, sum=0; for(i=0; i<4; ++i) { Roll[i] = rand()%NUMBER_OF_SIDES + 1; sum += Roll[i]; } // Find the smallest roll int smallest=Roll[0]; for(i=1;i<4;++i) { if(Roll[i] < smallest) { smallest = Roll[i]; } } // Subtract the smallest roll from the sum sum -= smallest; return sum; }int main( ){ srand( (unsigned)time(NULL) ); int strength = rollDice(); int dexterity = rollDice(); int charisma = rollDice(); int intelligence = rollDice(); return 0;}
and here's a version that does away with the array allocation and the second loop looking for smallest:
unsigned int rollDice() { const int NUMBER_OF_SIDES = 6; // Summate 4 dice rolls unsigned int sum=0; unsigned int smallest = NUMBER_OF_SIDES; for( unsigned int i=0; i<4; i++) { unsigned int roll = rand() % NUMBER_OF_SIDES + 1; sum += roll; if ( roll < smallest ) { smallest = roll; } } // Subtract the lowest roll sum -= smallest; return sum; }
[edited by - SDickson on April 11, 2004 3:06:27 PM]
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement