%g
描述说
Use the shortest representation:
%e
or%f
例如,
如果使用 %.6g
,544666.678
写成 544667
,这没问题。
但是当使用%.5g
时,同样的数字写成5.4467E+5
。
为什么这里使用指数表示法 (%e
) 而 544670
(%f
) 比它更短。
谁能帮我理解一下?这是错误吗?
类似地,44.35
在使用%.1f
时写成44.4
,这很好。
但是当使用%.1f
时,44.55
写成44.5
。为什么不写成44.6
呢?这是错误吗?
最佳答案
使用最短的表示:%e 或 %f 不够精确。
C11 7.21.6.1 The
fprintf
functionA
double
argument representing a floating-point number is converted in stylef
ore
(or in styleF
orE
in the case of aG
conversion specifier), depending on the value converted and the precision. LetP
equal the precision if nonzero,6
if the precision is omitted, or1
if the precision is zero. Then, if a conversion with style E would have an exponent ofX
:— if
P > X ≥ −4
, the conversion is with stylef
(orF
) and precisionP − (X + 1)
.— otherwise, the conversion is with style
e
(orE
) and precisionP − 1
.Finally, unless the
#
flag is used, any trailing zeros are removed from the fractional portion of the result and the decimal-point character is removed if there is no fractional portion remaining.
所以在 %.5g
和 544666.678
的例子中,P
是 5
,并且 X
为 5
,根据规则,使用 e
样式,因为 P > X ≥ −4
为假。
关于c - %g 在 printf 中的工作原理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34669026/