Tuesday, May 11, 2010

Floating Point Versus Integer Divide

Look at the program:
int main() {
float ans;
ans=5/10;
printf("%f",ans);
return 0;
}

what is the output?
The output is not like this: 0.50000

The output is 0.000000
because int/int = int

so change the program to
int main(void) {
float ans;
ans=5/10.0;
printf("%f",ans);
return 0;
}

the above program is (int/float)
so the output is now 0.500000

NOTE:
int/int = int
int/float = float
float/int = float
float/float = float

The above table can be summarized as: integer division takes place only when both elements are integers.

The below mentioned information is from: Practical C Programming, Third Edition - O'Reilly Media

The division operator is special. There is a vast difference between an integer divide
and a floating-point divide. In an integer divide, the result is truncated (any
fractional part is discarded). So the value of 19/10 is 1.

If either the divisor or the dividend is a floating-point number, a floating-point divide
is executed. So 19.0/10.0 is 1.9. (19/10.0 and 19.0/10 are also floating-point
divides; however, 19.0/10.0 is preferred for clarity.)


No comments:

Post a Comment