Search code examples
c++printfcoutzeroepsilon

difference in printing zero in cout and printf


with

printf("%lf\n",-1.0+0.9+0.1);

result is

0.000000

while with

cout<<-1.0+0.9+0.1;

result is

 2.77556e-17

again, if i change

 cout<<0.9+0.1+-1.0;

result is

 0

why this different behavior simply inverting the sum?and why 2.77556e-17?is it the machine epsilon?and why I get it and not zero?


Solution

  • std::cout by default for floating point variables is similar to the %g flag rather than the %lf flag in printf. In order to get the same behaviour, you have to pass std::fixed to the stream, e.g.:

    std::cout << std::fixed << 0.9+0.1+-1.0;