c++ - 在 C++ 中没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?

标签 c++ c++11 stl precision iomanip

如教程所示http://www.cplusplus.com/reference/iomanip/setprecision/

// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

int main () {
  double f =3.14159;
  std::cout << std::setprecision(5) << f << '\n';  // prints 3.1416 and not 3.141459 why 
  std::cout << std::setprecision(9) << f << '\n';
  std::cout << std::fixed;
  std::cout << std::setprecision(5) << f << '\n';
  std::cout << std::setprecision(9) << f << '\n';
  return 0;
}

std::cout << std::setprecision(5) 行不打印 5 个十进制数字,但在设置 std::fixed 后,setprecision 有效正如预期的那样。这是为什么 ?。

没有 std::fixedstd::setprecision() 有什么作用?

最佳答案

根据 http://en.cppreference.com/w/cpp/io/ios_base/precision ,精度决定打印多少位,而不是打印 float 后的多少位:

std::ios_base::precision

Manages the precision (i.e. how many digits are generated) of floating point output

这解释了舍入。

是的,使用 std::fixed 会改变浮点精度的解释。根据http://www.cplusplus.com/reference/ios/ios_base/precision/ :

In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The digits before the decimal point are not relevant for the precision in this case.

关于c++ - 在 C++ 中没有 **std::fixed** 的 **std::setprecision()** 的作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45084317/

相关文章:

c++ - 支持函数转换为引用类型、标准中的漏洞或编译器错误?

c++ - 从包中获取所有子包

c++ - Eigen eulerAngles() 返回不正确的值

C++11 STL 队列 emplace(Args&&... args) 和 swap(queue& x)

c++ - 为什么我不能在 gcc 的初始值设定项中访问默认参数?

c++ - 从字符串列表中找到最快的字符串

c++ - 鉴于这些条件,我可以使用 STL 进行线程化吗?

c++ - 一次性项目的脚手架/构建系统

c++ - 可变参数模板的模板模板参数扩展

c++ - 在 std::list 中查找