0

# why does this yields 0.00? why doesn't it yield 0.44 as it yields when float var=4.0/9.0 is used

float var = 4/9; printf("%.2 f\n", var) ;

3 Antworten

+ 4

Simba was correct, even though <var> was defined as `float`, the division operation in expression evaluated (4 / 9), had two integer operands, thus integer division took place.
You can achieve 0.44 by using floating point literal for either or both operands in the division. Apart from floating point literal, a floating point variable can also be used as an operand in an arithmetic operation.
All the below lines evaluate to 0.44. Notice that first two lines uses a floating point literal as either LHS (left hand side) or RHS (right hand side) operand; and the last line uses floating point literals for both the. LHS and RHS operand.
float var1 = 4.0 / 9;
float var2 = 4 / 9.0;
float var3 = 4.0 / 9.0;

+ 4

What you're doing here is integer division.
In C, a/b = 0 when a<b and a,b are integers.

0

Simba but i have declared it to be a float? it doesn't make sense ig