本文介绍了输出到具有精度的流浮点数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对浮点数精度有疑问:

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;
}

结果是:

所以,我的问题是为什么第一行中的数字这么短(我原本希望看到106.829)

gcc 4.1.2,我也在 LWS

进行了测试

解决方案

实际上,将106.829599舍入为6位数字(3位小数)是106.830,由于对 setprecision 只是最大值.

您可能正在寻找的是将setprecision与已修复结合在一起./p>

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:

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

解决方案

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.

这篇关于输出到具有精度的流浮点数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 12:09