关于c 11:c中没有** std :: fixed **的** std :: setprecision()**的作用是什么?

What is the role of **std::setprecision()** without **std::fixed** in c++?

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

中所示

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// setprecision example
#include <iostream>     // std::cout, std::fixed
#include <iomanip>      // std::setprecision

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

std :: cout << std :: setprecision(5)行不会打印5个十进制数字,但是在设置std :: fixed后,setprecision会按预期工作。这是为什么 ?。

不带std :: fixed的std :: setprecision()的作用是什么?


根据http://en.cppreference.com/w/cpp/io/ios_base/precision,精度决定要打印多少个数字,而不是浮点后要打印的数字:

std::ios_base::precision

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

这说明了四舍五入。

是的,使用std::fixed将更改对floatfield精度的解释。根据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.


精度的含义取决于是否使用固定,科学或默认格式。对于固定格式,它是小数点后的位数。对于科学来说,也是如此-但是,在该点之前总是只有一位数字;指数用于将小数点移到位置。对于默认格式,精度指定要打印的总位数(大约;这有点复杂)。

有关详细信息,请参见http://en.cppreference.com/w/cpp/io/c/fprintf,尤其是%f%e%g格式说明符的说明(有关固定的,科学的和默认格式)。指定std::cout << f的行为就像调用printf("%.<pre><format>", f)一样(至第一个近似值;现实再次复杂一些,但细节与当前问题无关),其中<pre1>setprecision<format>指定的数字是feg之一。


std::setprecision()的行为因所选格式而异。

std::fixed使std::setprecision()表示小数点后打印多少位。在将默认格式更改为std::fixed之前,先设置std::defaultfloat,然后std::setprecision()设置要打印的总位数,包括小数点前后的位数。

比较:

http://www.cplusplus.com/reference/ios/defaultfloat/

http://www.cplusplus.com/reference/ios/fixed/


这是因为"当floatfield设置为固定值时,将使用定点表示法写入浮点值:该值在小数部分中的位数与精度字段(精度)所指定的位数完全相同,并且用没有指数部分。"参考http://www.cplusplus.com/reference/ios/fixed/