Search code examples
ccastingtype-conversionaveragedivision

Type Casting in C resulting in zero


I have a simple C program where, I type cast two integers into float and then calculate their division. But, the type casting is resulting in zero. Kindly, a little help would be much appreciated.

'''

#include <stdlib.h>
#include <string.h>
#include<ctype.h>

float mean(float sum,float N); 
int main()
{
    int sum = 6;
    int N = 3;
    printf("\nsum: %d\nN: %d",sum,N);
    float m = mean((float)sum,(float)N);
    printf("\nMean: %d",m);
}
return 0;
}

float mean(float sum,float N){
    float m = sum / N;
    return m;
}

Here's the Output: Output


Solution

  • #include <stdlib.h>
    #include <string.h>
    #include<ctype.h>
    
    float mean(float sum,float N); 
    int main()
    {
        int sum = 6;
        int N = 3;
        printf("\nsum: %d\nN: %d",sum,N);
        float m = mean((float)sum,(float)N);
        printf("\nMean: %f",m);
    }
    return 0;
    }
    
    float mean(float sum,float N){
        float m = sum / N;
        return m;
    }
    

    %d prints an integer in base 10, %f prints a floating point value. So, for example if I used

    printf( "%d, %f\n", 9, 9.8 );
    

    The output would be 9, 9.800000. If you give printf 5.5 but use %d I think anything could happen.