简体   繁体   中英

How can I get the exact value of a double?

I have a situation where:

void foo( const double d )
{
    const double rounded_2_decimals = std::round(d*100.0) / 100.0;
    std::cout << "d=" << d << std::endl;
    std::cout << "r=" << rounded_2_decimals << std::endl;
}

When printed, d=3.125 , but r=3.12 instead of r=3.13 .

I suspect that is because the passed in d is actually 3.1249999.... This is why I put in the initial cout, so I could see the "true" value being passed in. Does std::cout round values before it displays them? How else could I see the "real" value being passed in?

Yes, std::cout does round values, however you can set a higher precision. First include the iomanip header. Then:

void foo( const double d )
{
    const double rounded_2_decimals = std::round(d*100.0) / 100.0;
    std::cout << "d=" << std::setprecision(9) <<  d << std::endl;
    std::cout << "r=" << std::setprecision(9) << rounded_2_decimals << std::endl;
}

Live example program here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM