如何使用cout以全精度打印双精度值?

So I've gotten the answer to my last question (I don't know why I didn't think of that). 因此,我已经得到了我
摘要由CSDN通过智能技术生成

本文翻译自: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;
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值