Reputation: 305
I want to see the number of times that the sum of two rolling dice appear. I'm writing the following code to show me the sum with myArray:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand (time(0));
int myArray[12];
for (int i =1; i < 10; i++)
{
int die_1 = rand() % 6 + 1;
int die_2 = rand() % 6 + 1;
myArray[(die_1 + die_2 - 2)]++;
cout<<endl<<"die_1 "<<die_1<<" die_2 "<<die_2<<" the sum: "<<die_1+die_2;
}
for (int i = 0; i < 12; i++)
cout<<endl<<myArray[i]<<" ";
}
but the code is returning weird results to me. Would appreciate any help to correct it.
Upvotes: 1
Views: 208
Reputation: 2005
You forgot to initialize your array (10) because the results are [2-12] so 10 answers :
int myArray[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
PS: to see your results I think it's better like
for (int i = 0; i < 11; i++)
cout << "for res[" << i + 2 << "]:\t" << myArray[i] << endl;
Upvotes: 4
Reputation: 13804
Intialize myArray with 0
memset(myArray, 0, sizeof(myArray));
otherwise, garbage value will effect the result.
Upvotes: 1