0

I have two code snippets and both produce different results. I am using TDM-GCC 4.9.2 compiler and my compiler is 32-bit version

( Size of int is 4 bytes and Minimum value in float is -3.4e38 )

Code 1:

int x;
x=2.999999999999999; // 15 '9s' after decimal point
printf("%d",x);

Output:

2

Code 2:

int x;
x=2.9999999999999999; // 16 '9s' after decimal point
printf("%d",x);

Output:

3

Why is the implicit conversion different in these cases?

Is it due to some overflow in the Real constant specified and if so how does it happen?

Alagusankar
  • 111
  • 1
  • 8
  • Possible duplicate of [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Thomas Jager Jun 07 '19 at 16:54
  • @ThomasJager Nope. That question discusses only the floating point arithmetic and not typecasting to int. – Alagusankar Jun 07 '19 at 17:01
  • It discusses the representation of floats as being the nearest representable value. – Thomas Jager Jun 07 '19 at 17:02
  • @ThomasJager Thanks for the mention – Alagusankar Jun 07 '19 at 17:07
  • Note: `2.999999999999999` and `2.9999999999999999` are both 'double' values, not 'float' To make them 'float' they should be written as: `2.999999999999999f` and `2.9999999999999999f` Note the trailing 'f'. So your actually working with `double` values, not `float` values – user3629249 Jun 07 '19 at 22:37

1 Answers1

5

(Restricting this answer to IEEE754).

When you assign a constant to a floating point, the IEEE754 standard requires the closest possible floating point number to be picked. Both the numbers you present cannot be represented exactly.

The nearest IEEE754 double precision floating point number to 2.999999999999999 is 2.99999999999999911182158029987476766109466552734375 whereas the nearest one to 2.9999999999999999 is 3.

Hence the output. Converting to an integral type truncates the value towards zero.

Using round is one way to obviate this effect.

Further reading: Is floating point math broken?

Bathsheba
  • 231,907
  • 34
  • 361
  • 483