output to stream float numbers with precision

折月煮酒 提交于 2019-12-10 14:56:04

问题


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


回答1:


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.

The decimal precision determines the maximum number of digits to be written on insertion operations to express floating-point values.

What you may be looking for is combining setprecision with fixed.



来源:https://stackoverflow.com/questions/9030329/output-to-stream-float-numbers-with-precision

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!