PDA

View Full Version : C++ Question of the Day


Brian
12-03-2002, 07:07 PM
Well everyone it's that time again to bail out the worst c++ programmer in the world. This is my first multiple .cpp and .h program. I think I have it all done, but the output is odd. it should read like this


Out of 200 Rolls of the 3 Dice

The dice Rolled 3: 1 Times
The dice Rolled 4: 5 Times
.
.
.
.
.
.
.
.
.
.
.
.
The dice Rolled 18: 3 Times


Here are the source files

DrJones
12-03-2002, 09:58 PM
First off i would move the srand(time(NULL)); part into the main function. There is only one random generator, seeding it 3 times makes no sense (currently it seeds when it creates the dice). I would just add that as the first thing in main and only do it there.

Next what your code does is roll the dice 200 times, outputing each new set of rolls into the next position in the array. IE if you rolled a 8, then a 12, then a 9, then a 16, your array would be..

num[0]=8
num[1]=12
num[2]=9
num[3]=16

What you want to do is keep a total of how many times that number came up. Solution is to create a different array. and do so:


int main()
{
srand(time(NULL));
int num[19] = {0};
DiceRoll MyDice;
int x;
for( x = 0; x < 200; x++)
{
MyDice.RollDice();
num[MyDice.ReportRoll()]++;
}

for(int i=0; i < 19;i++)
{
cout<<"The dice Rolled "<< i <<" : "<< num[i] <<" times"<< endl;
}

cout << endl << "total # of rolls: " << x << endl;
return 0;
}


for instance. That way you have an array with 19 positions representing the numbers 0-19. (technically you could do one with only 16 positions since you never will get a 0, 1 or 2, but i thought this way might be easier for you to understand. Now what you do is roll the dice, and what ever the output happens to be increase the array value at that point by one. Therefore in the array, that position will represent how many times that number came up. So num[3] is how many times 3 was gotten and num[7] is how many times 7 was gotten.

Does that help?