When you declare
int sum;
int counter;
...
then sum / counter
performs an integer division, resulting in an integer value. You can still assign that result to a float
variable, but the value will remain the integer part only.
To solve this, you need to cast either sum
or counter
to a float
- only then you are getting the float
value also as a result:
float result = (float) sum / counter;
This is, by the way, the same as ((float) sum) / counter
- means, the cast as you wrote it applies to sum
.