Search code examples
cfloating-pointdoubledecimal-point

Calculation issue with decimal places in C


I was trying to code a grayscale and have issues with the calculation. Can anyone explain why this returns 27.00000 instead of 27.66667?

#include <math.h>
#include <stdio.h>

int main(void)
{

    float count = ((27 + 28 + 28) / 3);
    printf("%f\n", count);

}

Solution

  • You forgot casting:

    int main()
    {
        float count = ((27 + 28 + 28) / (float)3);
        printf("%f\n", count);
    
        return 0;
    }
    

    Or:

    int main()
    {
        float count = ((27 + 28 + 28) / 3.0);
        printf("%f\n", count);
    
        return 0;
    }
    

    https://www.tutorialspoint.com/cprogramming/c_type_casting.htm