Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

c - Why Conversion Specification %lf does not work for Double in printf

I am writing a very small code just scanf and printf. I am reading a double value and printing it. The conversion specification %lf works properly to read a double value. But, it doesn't work with printf.

When I am trying to print that value I am getting output like 0.000000

double fag;
scanf("%lf", &fag);
printf("%lf", fag);

But, if I use %f in printf it works properly.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

The C standard library implementation you're using doesn't conform to C99 (or newer). The changes listed in the foreword (paragraph 5) contain:

%lf conversion specifier allowed in printf

The description of the l length modifier is (C99+TC3 7.19.6.1 par. 7, emphasis mine):

Specifies that a following d, i, o, u, x, or X conversion specifier applies to a long int or unsigned long int argument; that a following n conversion specifier applies to a pointer to a long int argument; that a following c conversion specifier applies to a wint_t argument; that a following s conversion specifier applies to a pointer to a wchar_t argument; or has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

%f and %lf are therefore equivalent. Both expect a double because arguments matching the ellipsis (the ... in int printf(char const * restrict, ...);) undergo the so-called default argument promotions. Among other things they implicitly convert float to double. It doesn't matter for scanf() since pointers aren't implicitly converted.

So if you can't or don't want to update to a newer C standard library %f can always be used in a printf() format string to print float or double. However in scanf() format strings %f expects float* and %lf expects double*.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...