Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why is this float changing after the return statement in C?

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 🙂

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading