我怎样才能得到双精度值?

How can I get the exact value of a double?

我的情况是:

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;
}

打印时,d=3.125,但 r=3.12 而不是 r=3.13

我怀疑这是因为传入的 d 实际上是 3.1249999.... 这就是我输入初始 cout 的原因,所以我可以看到传入的 "true" 值。 std::cout 会在显示值之前对其进行舍入吗?我还能如何看到传入的 "real" 值?

是的,std::cout 会舍入值,但是您可以设置更高的精度。首先包括 iomanip header。那么:

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;
}

实时示例程序here