My assignment was to do the following:
Write a program to simulate rolling a die 100 times and to display each outcome and a histogram of the outcome. Keep a count of the number of times each of the numbers 1,2,3,4,5,6 came up and call on a function printStars to display that number of stars followed by the count as follows:
Sample output:
Rolling die 100 times:
5 1 6 4 4 1 5 1 5 2 4 1 6 5 6 5 3 2 3 2 1 3 5 2 2 5 3 4 4 5 2 5 2 4 4 3 1 2 6 1
2 2 3 3 2 3 4 5 4 1 5 3 6 5 4 4 1 5 4 4 1 4 1 6 5 2 2 3 6 4 2 5 4 5 5 3 1 1 3 2
6 5 1 6 4 4 1 1 3 6 5 3 3 4 3 3 3 6 4 4
1: * * * * * * * * * * * * * * * * 15
2: * * * * * * * * * * * * * * * 14
3: * * * * * * * * * * * * * * * * * * 17
4: * * * * * * * * * * * * * * * * * * * * * 20
5: * * * * * * * * * * * * * * * * * * * 18
6: * * * * * * * * * * * 10
Press any key to continue . . .
My code isn't coming out right, I'm only getting stars for only one of the numbers and rest just show 0, how can I fix that issue, I've been trying to do it myself but everything I've done hasnt worked. Here's my code:
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 47 48 49 50 51 52 53 54 55 56 57 58
|
// Program to simulate rolling a die 100 times
#include<iostream>
#include<ctime>
#include<cstdlib>
using namespace std;
unsigned seed=time(0);
void printStars(int dieNum, int num);
int main()
{
srand(seed);
int die,roll, x1 = 0, x2 = 0, x3 = 0, x4 = 0, x5 = 0, x6 = 0;
cout<<"Rolling a die 100 times:"<<endl;
for(roll=0;roll<100;roll++)
{ die=1+rand()%6;
cout<< die <<" ";
}
cout<<endl;
for(roll = 0; roll < 100; roll++)
{
if(die== 1)
x1++;
else if(die== 2)
x2++;
else if(die== 3)
x3++;
else if(die== 4)
x4++;
else if(die== 5)
x5++;
else if(die== 6)
x6++;
}
cout << endl;
printStars(1, x1);
printStars(2, x2);
printStars(3, x3);
printStars(4, x4);
printStars(5, x5);
printStars(6, x6);
return 0;
}
void printStars(int dieNum, int num)
{
cout << dieNum << ": ";
for(int i = 0; i < num; i++)
cout << "* ";
cout << num << endl;;
}
|