输出到精确的流浮点数
我的浮点数精度有问题:
int main(void) {
double b = 106.829599;
float a = b;
std::cerr << std::setprecision(6) << "a = " << a << "; b = " << b << std::endl;
std::cerr << std::setprecision(7) << "a = " << a << "; b = " << b << std::endl;
}
结果是:
a = 106.83; b = 106.83
a = 106.8296; b = 106.8296
所以,我的问题是为什么第一行中的数字如此短(我期望看到 106.829)
gcc 4.1.2,我也在 LWS
I have a problem with float numbers precision:
int main(void) {
double b = 106.829599;
float a = b;
std::cerr << std::setprecision(6) << "a = " << a << "; b = " << b << std::endl;
std::cerr << std::setprecision(7) << "a = " << a << "; b = " << b << std::endl;
}
result is:
a = 106.83; b = 106.83
a = 106.8296; b = 106.8296
So, my question is why numbers in first line are so short (I was expecting to see 106.829)
gcc 4.1.2, also I made a test at LWS
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,106.829599 四舍五入到 6 位数字(3 位小数)是 106.830,由于 set precision 只是一个最大值。
您可能需要将 set precision 与 fixed 结合起来。
Actually, 106.829599 rounded to 6 digits (3 decimals) is 106.830, which is displayed as 106.83 since 6 digits precision given to setprecision is only a maximum value.
What you may be looking for is combining setprecision with fixed.