我的情况是:
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
在显示值之前对其进行舍入?我还能如何看到传入的“真实”值?
最佳答案
是的,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
关于c++ - 我怎样才能得到 double 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33574266/