Code won't display output.
May 26, 2012 at 3:33am UTC
So I'm working on this homework problem where I have to "roll two six-sided die" and allow the "user" to enter the number of times the dice is rolled and then display the results in a table format somewhat like this:
Sum Total Rolls
2 2
3 5
4 6
... etc.
The problem I'm having is that once the "user" enters the number of rolls, the table part won't display. Pointers?
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
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
using namespace std;
int main( )
{
unsigned long int mySum[12]={0},die_score[11]={0};
int die1, die2, sum, X;
srand(time(0));
cout << "Please enter number of times for dice to be rolled: " ;
cin >> X ;
for (int count=X;++X;)
{
die1=1+rand()%6;
die2=1+rand()%6;
++mySum[die1+die2];
}
cout<<"Sum" <<setw(8)<<"Total Rolls" << endl;
for (int j=2;j<13;++j)
cout<<j<<setw(8)<<mySum[j]<<endl;
}
May 26, 2012 at 3:41am UTC
You have an infinte loop in 19
May 26, 2012 at 3:46am UTC
How would I get rid of that?
May 26, 2012 at 3:49am UTC
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
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
using namespace std;
int main( ) {
unsigned long int mySum[12],die_score[11]; // Why die_score. You don't ever use it
int die1, die2, sum, X;
srand(time(0));
cout << "Please enter number of times for dice to be rolled: " ;
cin >> X ; // What happens if operator enters 20
for (int count=0; count < X; count++) {
die1 += rand()%6;
die2 += rand()%6;
mySum[count] = die1 + die2;
}
cout << "Sum" << setw(8) << "Total Rolls" << endl;
for (int j =2 ;j < 13; ++j) // Why j=2
cout << j << setw(8) << mySum[j] << endl;
return 0; // main should always return a value
}
This still doesn't work right, but I've commented the problem areas. It doesn't hang up now
May 26, 2012 at 3:55am UTC
The die score was something one of my classmates told me to put in. I got rid of it as you suggested. Changed mySum to a larger number, working fine now if I enter 20. :)
Thanks so much!
May 26, 2012 at 4:18am UTC
Could it be, this is what you were trying to do?
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
#include <iostream>
#include <stdlib.h>
#include <ctime>
#include <iomanip>
using namespace std;
int main( ) {
unsigned long int mySum = 0, count;
int die1, die2, X;
die1 = die2 = 0;
srand(time(0));
cout << "Please enter number of times for dice to be rolled: " ;
cin >> X;
for (count = 0; count < X; count++) {
cout << setw (5) << count + 1;
die1 = rand() % 6 + 1;
cout << setw (8) << die1;
die2 = rand() % 6 + 1;
cout << " +" << setw (2) << die2;
cout << " =" << setw (4) << die1 + die2 << "\n" ;
mySum += die1 + die2;
}
cout << "\n Grand Total = " << mySum << endl;
return 0;
}
Topic archived. No new replies allowed.