Hello folks I am having a really odd problem with the random number generator. For example when I set the max range to 6, I am getting some results that are 7.
Here is the class implementation where the function for rolling the dice is located. Pretty simple stuff
1 2 3 4 5 6 7 8 9 10 11 12 13 14
// Constructor
Die::Die()
{
sides = 0;
}
Die::Die(int dieSides)
{
sides = dieSides;
}
// Roll Function
int Die::roll()
{
return rand()& sides + 1;
}
In another file, for my Game class I have Die included as one of its member variables, such as
class WarGame
{
private:
int rounds;
int type1, type2;
string player1;
string player2;
int* player1Scores;
int* player2Scores;
Die* dice;
// This is the function for assigning the sides
void setSides(int);
// Here I am setting the sides
void WarGame::setSides(int sideTotal)
{
dice = new Die(sideTotal);
}
// Here I am calling the dice object to provide a score to the player
// Like mentioned before if I set the total sides to 4, some scores end up being 5.
void WarGame::simulateGame()
{
for (int x = 0; x < rounds; x++)
{
if (type1 == 1)
{
player1Scores[x] = dice->roll();
}
elseif (type1 == 2)
{
player1Scores[x] = dice2->rollLoaded(); // ignore this
}
}
}
Here is the output showcasing the error. As you can see in round 4 player 1 got a 7, even though the number of sides is set to 6
What is the number of sides each player will use? 6
What type of dice will player 1 use?
1. Regular Dice
2. Loaded Dice
1
What type of dice will player 2 use?
1. Regular Dice
2. Loaded Dice
1
How many rounds do you want the players to play? 4
Round 1
Player 1: 2
Player 2: 5
Round 2
Player 1: 0
Player 2: 6
Round 3
Player 1: 2
Player 2: 4
Round 4
Player 1: 7
Player 2: 1
Player 2 has won the game, congratulations
I never had this issue before working with random numbers, if anyone can point out why I this is happening it would be highly appreciated. Thanks
OMG no way wow, How was I not able to find that. I blame my IDE for not pointing it out LOL. In all seriousness though thanks a lot cire. Even though is irrelevant, curious to know what operation the & was doing there.
I appreciate you're just learning and playing, but I'd be remiss if I did not point you at this excellent talk about random values in C++, by Stephan T. Lavavej - he's a face on the C++ scene.