0

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);

}
Joesns
  • 45
  • 5
  • 3
    You are doing an `int/int` operation, hence the 27. Change it to `(27 + 28 + 28) / 3.0` or explicitly cast `(27+28+28) / ((float) 3)` – Pablo Jan 16 '21 at 19:16
  • there are lots of duplicates: [The sum of n terms of fractional expression is an integer when it should be a float](https://stackoverflow.com/q/60759755/995714), [Why dividing two integers doesn't get a float?](https://stackoverflow.com/q/16221776/995714) – phuclv Jan 17 '21 at 00:57

1 Answers1

2

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

Ido Levi
  • 114
  • 6
  • Thanks! That worked. Just to be on the safe side: Whenever I use a hardcoded number, it takes automatically an integer division unless I add a decimal point or (float) before the number? – Joesns Jan 16 '21 at 19:21
  • 2
    It depends by the operands' type. Between two integers the result will be an integer. Between an integer and a float the result will be a float. – Matteo Galletta Jan 16 '21 at 22:09
  • @chux-ReinstateMonica I was referring to the first example, where the number gets casted into a float. Referring to the second one, you're right. – Matteo Galletta Jan 18 '21 at 08:29
  • @MatteoGalletta You are correct. – chux - Reinstate Monica Jan 18 '21 at 14:31