0

Why does the following code print 0?

#include<cstdio>

int main()
{
    float a = 0.1;
    printf("%d", int(2 - a * a * 100));
    return 0;
}
lkdx2
  • 1
  • 9
    Does this answer your question? [Is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken) – Passerby Jan 24 '22 at 12:41
  • 2
    0.1 is periodic in binary, so cannot represented exactly as float, instead it is rounded – and obviously in your case slightly larger than 0.1, resulting in (0.1 + e) * (0.1 + e) * 100, giving a result slightly larger than 1, thus the difference is slightly smaller than 1, thus converted to 0. – Aconcagua Jan 24 '22 at 12:45
  • 1
    Conclusion: If you rely on *exact* math floating point is a rather bad choice... – Aconcagua Jan 24 '22 at 12:47

0 Answers0