Code simulates the rolling of two die 36000 times and outputs "Sum = _; Frequency = _; Percentage = _". Compiled code outputs everything correctly except percentage. "Percentage = 0" when it should output the quotient of "(frequency[calcCount] /36000) * 100" Is this a conflict in data type? How can I properly output the quotient?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SUM_SIZE 36000
#define FREQUENCY_SIZE 13
int main(void){
int rollCount; // counter to loop through 36000 rolls of dice & sums
int calcCount; //counter to loop through frequencies 1-12 of sum calculation
//initialize frequency counters to 0
int frequency[FREQUENCY_SIZE] = {0};
//calculation array
int calculation[SUM_SIZE];
//seed
srand((unsigned)(time(NULL)));
for (rollCount = 1; rollCount <= SUM_SIZE; rollCount++){
//rolling first die
int face1 = (1 + ( rand() % 6));
//rolling second die
int face2 = (1 + ( rand() % 6));
int sum = face1 + face2;
//initializing array elements
calculation[rollCount] = sum;
//for each roll, select value of an element of array calculation
//and use that value as subscript in array frequency to determine
//element to increment (which in this case is the sum frequency)
++frequency[calculation[rollCount]];
}
//displaying results
for (calcCount = 2; calcCount < FREQUENCY_SIZE; calcCount++){
//calculating percentage
int percentage = (frequency[calcCount] /36000) * 100;
printf("Sum = %d; Frequency = %d; Percentage = %d \n", calcCount, frequency[calcCount], percentage);
}
}
When you do a division between two integers, the result will also be an integer and the "exact" result is truncated to fit an integer. Examples:
3/2 -> 1
10/3 -> 3
5/10 -> 0
and when you do
int percentage = (frequency[calcCount] /36000) * 100;
the part frequency[calcCount] /36000
is calculated first. It is a division between two int
and it will give the result zero because frequency[calcCount]
is less than 36000
. Consequently multiplying with 100 still gives zero.
Instead do the multiplication first - like:
int percentage = (100 * frequency[calcCount]) /36000;
Another alternative is to use floating point like:
double percentage = (frequency[calcCount] /36000.0) * 100;
^^^
Notice the .0 to make 36000 a double
but then you need to change the print to use %f
double percentage = (frequency[calcCount] / 36000.0) * 100;
printf("Sum = %d; Frequency = %d; Percentage = %.2f \n", calcCount, frequency[calcCount], percentage);
^^^
Notice this to print the double