Why does (int)55 == 54 in C++?

Casting to int truncates the number - same as if you'd called floor(currentFib). So even if currentFib is 54.999999... (a number so close to 55 that it will be rounded up when printed), (int)currentFib will produce 54.


Due to floating point rounding, that 55 row is computing something like 54.99999. Casting double to int truncates the .99999 right off.

On my machine, printing a column displaying (currentFib-(int)currentFib) shows errors on the order of 1.42109e-14. So it's more like 0.999999999999986.


Okay, short answer is that under no condition should (int)55 == 54, so you need to start asking yourself what the associated line of code is really doing.

First question: how strongly does == bind compared to a typecast?

Tags:

C++

Fibonacci