This is a very simple code, it’s goal is to calculate the average of an array of grades (integers):
#include <stdio.h>
int calculateAverage(int grades[], int size){
int sum = 0;
for (int index = 0; index < size; index++) {
sum += grades[index];
}
float average = (float)sum / size;
printf("\nAverage: %f", average);
return average;
}
void printAverage(int grades[], int size){
printf("Grades: \n");
for (int index = 0; index < size; index++) {
printf("%d\n", grades[index]);
}
float average = calculateAverage(grades, size);
printf("\nAverage: %f", average);
}
int main() {
int grades[] = {4, 6, 10, 2, 8, 9, 10, 7, 8, 5};
size_t grades_size = sizeof(grades)/sizeof(grades[0]);
printAverage(grades, grades_size);
}
When I print out the average in the calculateAverage function, the output is 6.9 (correct). However, after the average is returned to the printAverage function, the average is now 6.0, which makes no sense to me.
Any help is appreciated, thanks 🙂
>Solution :
int calculateAverage(int grades[], int size)
this function return int value, change it to this:
float calculateAverage(int grades[], int size)
then you can get float return