Why float data type treats X/Y (Eg 5/9) and X.0/Y.0 (Eg 5.0/9.0) differently?

Viewed 201

I was working on this code in C language and was unable to understand the reason for getting different answer for these two codes.

first writing values without decimal point

float num2=(5/9);

this gave me the output as the following:

0.000000

with decimal point

float num2=(5.0/9.0);

this gave me the output as the following:

0.555556

what is the working or theory behind this difference of answers?

3 Answers

5 and 9 both are integers. So, the result of 5/9 is 0. Everything is done here at the integer level and then put into the float num2 variable. For getting the actual real answer 0.555556 you need to have at least one of the numbers as a float or a real. 5.0/9 or 5/9.0 or type casting one of them, (float)5/9 would also work.

The theory is, the numbers are sort of converted/upscaled to higher data type (forgot the proper terminology). Like in case of 5/9.0, the 5 here is first converted to 5.0 and then the division operation done. So, C is not looking at the left hand side of the instruction while doing the right hand side operation.

C considers 5 and 9 as an integers, as they are. So it does the operation in integer level, that is 5/9 is indeed zero. Than, this result is assigned to the num2 variable.

Whe you write 5.0/9, than C sees that 5.0 is a floating point value, so it will do the operation in float, which will give you a different result, and this now this result will be assigned to your num2.

You can also write this

num2=(float)5/9; //or
num2=5/(float)9; //or
num2=5/9.0;

Either way, you promote one operand to float level, so the whole operation will happen on float level.

C evaluates expressions from the “bottom” up.

At the top, the declaration float num2=(5/9); contains the expression (5/9). That expression contains 5/9. That expression uses the operator / on the operands 5 and 9. These operands are at the bottom.

5 and 9 are literals with type int. 5/9 is evaluated using int arithmetic. The result is an int value of zero. Then the parentheses are evaluated, so (5/9) is effectively (0), and so it is zero. Then this zero is converted to float to be used to initialize num2.

Because expressions are evaluated from the bottom up, they are affected by the operands they use. They are not affected by the context they are in. The fact that an expression will eventually be assigned to a float does not cause it to be evaluated using float.

Related