Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
445 views
in Technique[技术] by (71.8m points)

c - 正确的格式说明符用于printf中的double(Correct format specifier for double in printf)

What is the correct format specifier for double in printf?

(printf中double的正确格式说明符是什么?)

Is it %f or is it %lf ?

(是%f还是%lf ?)

I believe it's %f , but I am not sure.

(我相信是%f ,但我不确定。)

Code sample (代码样例)

#include <stdio.h>

int main()
{
   double d = 1.4;
   printf("%lf", d); // Is this wrong?
}
  ask by Leopard translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

"%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 ,因为如果你试图传递一个floatprintf ,它会被提升到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 ,它的价值是,对于printfscanf使用%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”),但是效果是相同的:所有可变参数在被函数接收之前都经过默认提升。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...