c - Average of an array displays correctly only if casted to float -


So I have a beautiful Nobis Question though I declare the average as a float, when I call it Avg = sum / counter; I calculate , where counter is the number of elements greater than 0 in an array, and then print it, after me only 0 decimal point

However if I calculate it by casting it on float, avg = (float) yoga / counter; , the average is properly printed.

Should not the first one be correct? If I declare a float as a float, then why should I put it in a float later?

when you declare

  int sum; Int counter; ...   

then sum / counter divides an integer, which results in an integer value. You can still specify that result in the float variable, but the value will remain only integer part.

To solve this, you have to put sum or counter in a float - you are getting it As a result the float value too:

  float result = (float) sum / counter;   

By the way, as (float) amount) / counter - means that, as you type, that is on Applies yoga .

Comments

Popular posts from this blog

Java - Error: no suitable method found for add(int, java.lang.String) -

java - JPA TypedQuery: Parameter value element did not match expected type -

c++ - static template member variable has internal linkage but is not defined -