I am trying to write a program, which rolls a die twice using the rand()
function in C. My aim is to roll the die 36000 times and find the sum of the two results obtained (from the two die) each time and store the sum (of the two results which lie in the range [2,12]) in an array and display the result using for
loop and printf()
function.
From the concept of probability I expect the following result:
<table>
<tr>
<th>Sum</th>
<th>No.</th>
</tr>
<tr>
<td>2</td>
<td>1000</td>
</tr>
<tr>
<td>3</td>
<td>2000</td>
</tr>
<tr>
<td>4</td>
<td>3000</td>
</tr>
<tr>
<td>5</td>
<td>4000</td>
</tr>
<tr>
<td>6</td>
<td>5000</td>
</tr>
<tr>
<td>7</td>
<td>6000</td>
</tr>
<tr>
<td>8</td>
<td>5000</td>
</tr>
<tr>
<td>9</td>
<td>4000</td>
</tr>
<tr>
<td>10</td>
<td>3000</td>
</tr>
<tr>
<td>11</td>
<td>2000</td>
</tr>
<tr>
<td>12</td>
<td>1000</td>
</tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Now, this is the code I put
int main(void)
{ srand(3);
int die1, die2, count, measure[13];
for(count=0; count<36000; count ){
die1=1 rand()%6;
die2=1 rand()%6;
measure[die1 die2] ;
}
printf("Results!\n");
printf("Sum s\n", "Frequency");
for(count=2; count<=12; count ){
printf("= d\n", count, measure[count]);
}
return 0;
}
This was the result I got -The result I obtained
From the image, all the values from 2 to 12 are close to the expected values except 6 and 12. For 6 and 12 it shows 4204735 and 11147179 as the values both of which are far more than 36000. I am unable to understand the reason behind this absurd result.
CodePudding user response:
You haven't initialized your array:
int measure[13];
So now, measure
is uninitialized, so it can have some random garbage values
You have to initialize your array with zeros, like this:
int measure[13] = {0};
Alternatively, you could use memset
, but I wouldn't recommend it:
int measure[13];
memset(measure, 0, sizeof measure);