c++ - Why cout's default precision doesn't effect evaluated result? -
here thinking:
#include <iostream> #include <iomanip> int main () { double x = 10-9.99; std::cout << x << std::endl; std::cout << std::setprecision (16); std::cout << x; return 0; }
the above program prints 0.01 evaluating x before setprecision () , long number not equal 0.01, x after setprecision ().cout has default precision of 16 when printing floating point numbers in machine. if precision 16, above value should 0.0100000000000000 remains 0.01but when setprecision () 16, program prints long number containing 16 digits. question is, why cout doesn't prints digits according types default precision. why need force cout (by using setprecision ()) print digits?
why cout doesn't prints digits according types default precision.
if use std::fixed
setprecision
, display however-many digits precision asks for, without rounding , truncating.
as why rounding accounts output...
let's code print couple other things too:
#include <iostream> #include <iomanip> int main () { double x = 10-9.99; std::cout << x << '\n'; std::cout << std::setprecision (16); std::cout << x << '\n'; std::cout << 0.01 << '\n'; std::cout << std::setprecision (18); std::cout << x << '\n'; std::cout << 0.01 << '\n'; std::cout << x - 0.01 << '\n'; }
and output (on 1 specific compiler/system):
0.01 // x default 0.009999999999999787 // x after setprecision(16) 0.01 // 0.01 after setprecision(16) 0.00999999999999978684 // x after setprecision(18) 0.0100000000000000002 // 0.01 after setprecision(18) -2.13370987545147273e-16 // x - 0.01
if @ how 0.01 directly encoded @ 18 digit precision...
0.0100000000000000002 123456789012345678 // counting digits
...we can see why truncated "0.01"
during output @ precision 17.
you can see there's different value in x
created directly coding 0.01
- that's allowed because it's result of calculation, , dependent on double
or cpu-register approximation of 9.99
, either or both of have caused discrepancy. error enough prevent rounding "0.01"
@ precision 16.
unfortunately, kind of thing normal when handling double
s , float
s.
Comments
Post a Comment