views:

103

answers:

4

int a=7 int b=10 float answer = (float)a/b;

answer=0.699999988 ( I expect 0.7 ??)

A: 

It is because floating point calculations are not precise.

5ound
+3  A: 

The short version is: Floating points are not accurate, it's only a finite set of bits, and a finite set of bits cannot be used to represent an infinite set of numbers.

The longer version is here: http://docs.sun.com/source/806-3568/ncg_goldberg.html

See also:

http://stackoverflow.com/questions/56947/how-is-floating-point-stored-when-does-it-matter

http://stackoverflow.com/questions/2509576/why-is-my-number-being-rounded-incorrectly

nos
+1  A: 

Floating point numbers are accurate only to a certain finite number of digits of precision. You will need to do some rounding to get whole numbers.

If you need more precision, use the double data type, or the NSDecimal class (Which will preserve your decimal digits at the expense of complexity).

futureelite7
A: 

The only thing I rely on is the existence of exact small integers (namely -2, -1, 0, 1, 2, as you might use for representing [0,1] plus some special values), and some people frown on using that too.

tc.