在c ++中setprecision是否圆?如果是这样为什么我看到这个? [英] Does setprecision in c++ round? If so why am I seeing this?

查看:201
本文介绍了在c ++中setprecision是否圆?如果是这样为什么我看到这个?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下片段在我预期为0.29848时输出0.29847:

The following snippet outputs 0.29847 when I would have expected 0.29848:

double f = 0.298475;
cout << setprecision(5) << f << endl;

然而,对于其他示例,我观察四舍五入:

For other examples, however, I observe rounding:

double f = 0.123459;
cout << setprecision(5) << f << endl;

输出:0.12346

outputs: 0.12346

p>

and

double f = 0.123454;
cout << setprecision(5) << f << endl;

输出:0.12345

outputs: 0.12345

推荐答案

0.298475 的数字不能在 double 其分母是2的幂,为11939/40000),并且存储的实际号实际上更接近0.29847而不是0.29848。

The number 0.298475 isn't representable exactly in a double (since it's not a fraction whose denominator is a power of two, being 11939/40000), and the actual number that is stored is actually closer to 0.29847 than to 0.29848.

这篇关于在c ++中setprecision是否圆?如果是这样为什么我看到这个?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆