Question

So I have a pretty noobish question. Although I declare the average as a float, when I calculate it avg = sum / counter;, where counter is the number of elements bigger than 0 in an array, and then print it, I get only 0s after the decimal point.

However if I calculate it by casting to a float, avg = (float) sum/counter;, the average is printed out correctly.

Shouldn't the first one be correct? If I declare a variable as a float, why should I cast it later to a float again?

Was it helpful?

Solution

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.

OTHER TIPS

The cast as you wrote it applies to sum, not to avg, the result you obtain is perfectly normal if sum is an integer type.

The operator / applied to two integers performs integer division. The operator / applied to two floating point values performs floating point division. If one value is floating point, the other is promoted to floating point. But if both are integer, integer division is performed.

Later, the result of this operation, which already exists in memory, is assigned to another variable. But that is another story. You need to get the correct result in the first place, and then you can assign it to a variable which will store it.

The problem is sum is of type integer so it rounds of to 0's after the decimal point.It does not automatically type cast.So either declare sum as float or manually type cast the result as float

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top