Put simply, the following code compiles, but does not work, and I have no clue why (despite reading extensively about rand()). In the interest of full disclosure, this is for a school project.
Code:
/*
* Dice.c
* CMSC 245, Professor [REDACTED]. Project 5.
*
* [REDACTED] <[REDACTED]>
*
* This program simulates rolling 100,000 die, prints the number of times a 2,
* 7 and 12 were rolled and prints the average of all the rolls.
*/
#include <stdio.h>
#include <stdlib.h>
void printHeading();
int rollDie();
int main() {
int i, j, seed, temp;
const int dice = 2;
/* The array store will always hold 6*(# of Dice) - (# of Dice) + 1 numbers.
*/
int store[(6*dice)-(dice-1)];
printf("Enter a seed:\t");
scanf("%d", &seed);
srand( seed );
for(i = 0; i <= 100000; i++) {
temp = rollDie() + rollDie();
store[temp-2]++;
}
for(j = 0; j < 11; j++) {
printf("%d ", store[j]);
}
}
int rollDie() {
/* It is best to discard any values outside the range you want so that the
* probabilities for each number coming up are not affected, but that takes
* far too long, so we use the modulus operator.
*/
return (1 + (rand() % 6));
}
For example, I had the following (very clearly impossible) set returned for a seed of 1:
Code:
2761, 5546, 8388, 11209, 1987762146, 49553, 662080544, 43823, 8439, 5462, 4199134,
The values 1987762146 (i.e. number of 6's) and 662080544 (number of 8's) change a lot with the same seed, while 43823 (number of 9's) changes slightly (which I still isn't supposed to happen?). The last value (number of 12's) doesn't budge, but is impossible to obtain with my constraints.
Anyway, I'd really appreciate any help as to why this isn't working. Thanks in advance.