difference in printing zero in cout and printf

165 views Asked by At

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?

1

There are 1 answers

0
Rapptz On BEST ANSWER

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;