本文翻译自:How do I print a double value with full precision using cout?
So I've gotten the answer to my last question (I don't know why I didn't think of that). 因此,我已经得到了我最后一个问题的答案(我不知道为什么我没有想到这一点)。 I was printing a double
using cout
that got rounded when I wasn't expecting it. 我正在使用使用cout
打印的double
cout
,当我没想到时会四舍五入。 How can I make cout
print a double
using full precision? 如何使cout
以全精度打印double
?
#1楼
参考:https://stackoom.com/question/2K8V/如何使用cout以全精度打印双精度值
#2楼
With ostream::precision(int) 使用ostream :: precision(int)
cout.precision( numeric_limits<double>::digits10 + 1);
cout << M_PI << ", " << M_E << endl;
will yield 将产生
3.141592653589793, 2.718281828459045
Why you have to say "+1" I have no clue, but the extra digit you get out of it is correct. 为什么您必须说“ +1”我不知道,但是您从中得到的多余数字是正确的。
#3楼
printf("%.12f", M_PI);
%.12f表示浮点数,精度为12位数字。
#4楼
By full precision, I assume mean enough precision to show the best approximation to the intended value, but it should be pointed out that double
is stored using base 2 representation and base 2 can't represent something as trivial as 1.1
exactly. 就全精度而言,我假设平均精度足以显示与预期值的最佳近似值,但是应该指出,使用基数2表示存储double
精度数,而基数2不能精确表示1.1
。 The only way to get the full-full precision of the actual double (with NO ROUND OFF ERROR) is to print out the binary bits (or hex nybbles). 获得实际双精度全精度的唯一方法(不带ROUND OFF ERROR)是打印出二进制位(或十六进制小数位)。 One way of doing that is writing the double
to a union
and then printing out the integer value of the bits. 一种方法是将double
写入并union
,然后打印出这些位的整数值。
union {
double d;
uint64_t u64;
} x;
x.d = 1.1;
std::cout << std::hex << x.u64;