This is supposed to simulate 2 6-sided dice being thrown, adding +1 to an element of an array acquainted with the result. E.g: a[4] holds how many 4’s are rolled. For some reason, no matter how many times it rolls, it gives me 1 for every element in the array. I.e: (a[2] = 1, a[3] = 1, a[4] = 1, etc.)
#include <iostream>
#include <cmath>
#include <cstdlib>
#include <ctime>
using namespace std;
int throwDice() // generates random number ranging 2-12
{
int x = (rand() % 6) + 1;
int p = (rand() % 6) + 1;
return x + p;
}
int main()
{
srand (time(NULL));
int y;
cout << "Roll dice how many times?" << endl;
cin >> y;
int a2[12]; // initializes and declares elements a[2] - a[12] with value 0
for (int i = 2; i <= 12; i++)
a2[i] = 0;
for (int i = 0; i <= y; i++) // runs random number generator, adds +1 to that element
{
a2[throwDice()]++;
}
for (int i = 2; i <= 12; i++) // prints how many results per element
cout << i << " = " << throwDice[i] << endl;
system("pause");
}
should be
You should always use
-Wallwhen compiling your code, that would have shown you immediately that something is wrong:Also, array indices start at 0, so to be able to access
a2[12], it has to have size 13 at least.Finally,
system("pause");is a questionable idea. I’d prefercin.get();to wait for the user to press any key.