Correct format specifier for double in printf

后端 未结 5 1069
遇见更好的自我
遇见更好的自我 2020-11-22 06:01

What is the correct format specifier for double in printf? Is it %f or is it %lf? I believe it\'s %f, but I am not sure.<

5条回答
  •  情话喂你
    2020-11-22 06:08

    Given the C99 standard (namely, the N1256 draft), the rules depend on the function kind: fprintf (printf, sprintf, ...) or scanf.

    Here are relevant parts extracted:

    Foreword

    This second edition cancels and replaces the first edition, ISO/IEC 9899:1990, as amended and corrected by ISO/IEC 9899/COR1:1994, ISO/IEC 9899/AMD1:1995, and ISO/IEC 9899/COR2:1996. Major changes from the previous edition include:

    • %lf conversion specifier allowed in printf

    7.19.6.1 The fprintf function

    7 The length modifiers and their meanings are:

    l (ell) Specifies that (...) has no effect on a following a, A, e, E, f, F, g, or G conversion specifier.

    L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to a long double argument.

    The same rules specified for fprintf apply for printf, sprintf and similar functions.

    7.19.6.2 The fscanf function

    11 The length modifiers and their meanings are:

    l (ell) Specifies that (...) that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to double;

    L Specifies that a following a, A, e, E, f, F, g, or G conversion specifier applies to an argument with type pointer to long double.

    12 The conversion specifiers and their meanings are: a,e,f,g Matches an optionally signed floating-point number, (...)

    14 The conversion specifiers A, E, F, G, and X are also valid and behave the same as, respectively, a, e, f, g, and x.

    The long story short, for fprintf the following specifiers and corresponding types are specified:

    • %f -> double
    • %Lf -> long double.

    and for fscanf it is:

    • %f -> float
    • %lf -> double
    • %Lf -> long double.

提交回复
热议问题