luyi0619's blog

By luyi0619, 12 years ago, In English

I found that "lf" is ok for GNU C++ and MS C++, but not ok for C++ 0x using printf. Also, "f" works well for them.

float and double both use "f" ?

How about scanf ?

Could any body offer me some references?

  • Vote: I like it
  • 0
  • Vote: I do not like it

»
12 years ago, # |
  Vote: I like it +7 Vote: I do not like it

%f is for float only. %lf is for double. It's both for scanf and printf.

  • »
    »
    12 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    however, if you use lf for double in c++ 0x , it does not work.

    • »
      »
      »
      12 years ago, # ^ |
      Rev. 2   Vote: I like it 0 Vote: I do not like it

      If you use GCC, you can add -D__USE_MINGW_ANSI_STDIO=0 parameter to compilation command line and %lf will work quite OK.

      • »
        »
        »
        »
        12 years ago, # ^ |
          Vote: I like it 0 Vote: I do not like it

        I guess problem is that you can't change compilation params on CF

»
12 years ago, # |
Rev. 2   Vote: I like it +6 Vote: I do not like it

To operate on double, use %f or %lf with printf(), but only %lf with scanf(). Reference: the C99 standard, 7.19.6.1.7, 7.19.6.1.8 and 7.19.6.2.11. C++11 is based on C99 (1.1.2) and includes its standard library (17.2, 27.9.2). So the same format must work for C++11, too.

If it does not work, then your C++ implementation might not be fully conformant.

»
12 years ago, # |
Rev. 3   Vote: I like it 0 Vote: I do not like it

Traditionally, only %f can be used in printf for printing doubles and floats. The main idea is that when passing any floating-point numbers (float or double) to variadic functions like printf they are automatically promoted to double, so you don't have to (or can't) distinguish double from float and only one format specifier is used in printf. But this confused some people, so the new version of C (but not the current version of C++) allows the use of %lf for doubles in printf.