"%f"
is the (or at least one) correct format for a double.
("%f"
是双精度的(或至少一种)正确格式。)
There is no format for a float
, because if you attempt to pass a float
to printf
, it'll be promoted to double
before printf
receives it 1 . (有一个无格式的float
,因为如果你试图传递一个float
到printf
,它会被提升到double
之前printf
接受它1。)
"%lf"
is also acceptable under the current standard -- the l
is specified as having no effect if followed by the f
conversion specifier (among others). (在当前标准下, "%lf"
也是可以接受的-如果l
后面跟随f
转换说明符(除其他外),则l
被指定为无效。)
Note that this is one place that printf
format strings differ substantially from scanf
(and fscanf
, etc.) format strings.
(请注意,这是printf
格式字符串与scanf
(和fscanf
等)格式字符串大不相同的地方。)
For output, you're passing a value , which will be promoted from float
to double
when passed as a variadic parameter. (对于输出,您正在传递一个value ,当作为可变参数传递时,该值将从float
提升为double
。)
For input you're passing a pointer , which is not promoted, so you have to tell scanf
whether you want to read a float
or a double
, so for scanf
, %f
means you want to read a float
and %lf
means you want to read a double
(and, for what it's worth, for a long double
, you use %Lf
for either printf
or scanf
). (对于输入,您要传递未提升的指针 ,因此必须告诉scanf
是要读取float
还是double
,因此对于scanf
, %f
表示要读取float
, %lf
表示要读取float
读取double
(对于一个long double
%Lf
,它的价值是,对于printf
或scanf
使用%Lf
)。)
1. C99, §6.5.2.2/6: "If the expression that denotes the called function has a type that does not include a prototype, the integer promotions are performed on each argument, and arguments that have type float are promoted to double. These are called the default argument promotions."
(1. C99,第6.5.2.2/6节:“如果表示被调用函数的表达式的类型不包含原型,则对每个参数执行整数提升,而将类型为float的参数提升为双精度。这些称为默认参数提升。”)
In C++ the wording is somewhat different (eg, it doesn't use the word "prototype") but the effect is the same: all the variadic parameters undergo default promotions before they're received by the function. (在C ++中,措词有些不同(例如,它不使用单词“ prototype”),但是效果是相同的:所有可变参数在被函数接收之前都经过默认提升。)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…