rand() not printing correct #s for dice?
Jun 14, 2016 at 1:33pm UTC
Hello all,
I'm pretty new to C++. I've just done a ton of research to build a program that rolls 2 sets of dice 36000 times and then stores the different combinations into a 2D array. The first row is all the rolls from dice1 and the second row is the rolls from dice2.
The only problem I'm having at this point is that I can't keep the random numbers between 1 and 6 for the die. I've tried using rand() with and without the +1, and I've been unsuccessful at finding a solution to this so far. Any help (not too advanced, please) is appreciated.
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
#include<iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main(){
srand(time(0));
int count = 0;
const int column_size = 36;
const int row_size = 2;
int dice[row_size][column_size];
while (count<36000){
dice[rand()%6][rand()%6];
count++;
}
for (int row = 0; row<row_size; row++){
for (int column = 0; column<column_size; column++){ //Printing the array
cout<<dice[row][column]<<" " ;
}
cout<<endl;
}
return 0;
}
I have also tried using this instead:
1 2 3 4 5 6 7
while (count<36000){
die1 = rand()%6+1;
die2 = rand()%6+1;
dice[die1][die2];
count++;
}
Last edited on Jun 14, 2016 at 1:57pm UTC
Jun 14, 2016 at 2:00pm UTC
First off line 15 is bogus. You're generating two indexes, each of which is from 0-5. (6x6).
However, your array is declared as [2][36].
Your declaration of your array (dice) doesn't match your problem statement.
That implies more than two dice. Did you mean a "a set of 2 dice"?
If you're trying to count how many times each combination comes up in 36,000 rolls, a simple 6x6 array is sufficient.
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
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <iomanip>
using namespace std;
int roll_die ()
{ return rand()%6;
}
int main()
{ srand((unsigned )time(0));
int count = 0;
int roll1, roll2;
const int FACES = 6;
int dice[FACES][FACES];
// Initialize the array
for (int i=0; i<FACES; i++)
for (int j=0; j<FACES; j++)
dice[i][j] = 0;
while (count<36000)
{ roll1 = roll_die();
roll2 = roll_die();
dice[roll1][roll2]++;
count++;
}
for (int row = 0; row<FACES; row++)
{ for (int column = 0; column<FACES; column++)
cout << setw(6) << dice[row][column] << " " ;
cout << endl;
}
system ("pause" );
return 0;
}
Last edited on Jun 14, 2016 at 2:03pm UTC
Topic archived. No new replies allowed.