c++ - Setprecision is Confusing -
i want ask setprecision because i'm bit confused.
here's code:
#include <iostream> #include <iomanip> using namespace std; int main() { double rate = x; cout << fixed << setprecision(2) << rate; } where x = following:
the left side of equation values of x.
1.105 = 1.10 should 1.11
1.115 = 1.11 should 1.12
1.125 = 1.12 should 1.13
1.135 = 1.14 correct
1.145 = 1.15 correct
but if x is:
2.115 = 2.12 correct
2.125 = 2.12 should 2.13
so why in value it's correct it's wrong?
please enlighten me. thanks
there no reason expect of constants in post can represented exactly using floating-point system. consequence, exact halves have may no longer exact halves once store them in double variable (regardless of how iostreams meant round such numbers.)
the following code illustrates point:
#include <iostream> #include <iomanip> using namespace std; int main() { double rate = 1.115; cout << fixed << setprecision(20) << rate; } output:
1.11499999999999999112 i recommend taking @ faq.
Comments
Post a Comment