I am just starting out with Objective-C,and with C in general,so I suppose this is a C question as well.It's more of a why question rather than a how question.
I noticed that while dividing two integers ,the decimal part is rounded down to 0
even though the result is a float.The sources I followed suggest the following approach to deal with this:
float result = (float) numerator / denominator;
I want to know now why this works. Two things especially.1) if you have to cast the numerator, why don't you have to cast the denominator as well? 2) Why can't you just cast the whole thing? What I tried first was
float result = (float) (numerator / denominator);
But this again rounded the decimal part to 0
. What is the reason?
By promoting the numerator to float, you require the denominator to be promoted, as well. However, when you place the two in parens, then you are telling the compiler to do the division as integers then cast the resulting (potentially truncated) integer to float.