How to 'cout' the correct number of decimal places of a double value?

前端 未结 9 1833
迷失自我
迷失自我 2020-11-27 07:44

I need help on keeping the precision of a double. If I assign a literal to a double, the actual value was truncated.

int main() {
    double x =         


        
9条回答
  •  情话喂你
    2020-11-27 08:08

    Due to the fact the float and double are internally stored in binary, the literal 7.40200133400 actually stands for the number 7.40200133400000037653398976544849574565887451171875

    ...so how much precision do you really want? :-)

    #include     
    int main()
    {
        double x = 7.40200133400;
        std::cout << std::setprecision(51) << x << "\n";
    }
    

    And yes, this program really prints 7.40200133400000037653398976544849574565887451171875!

提交回复
热议问题