How does this program work?

前端 未结 13 2072
闹比i
闹比i 2020-11-30 22:44
#include 

int main() {
    float a = 1234.5f;
    printf(\"%d\\n\", a);
    return 0;
}

It displays a 0!! How is that

相关标签:
13条回答
  • 2020-11-30 23:28

    That's because %d expects an int but you've provided a float.

    Use %e/%f/%g to print the float.


    On why 0 is printed: The floating point number is converted to double before sending to printf. The number 1234.5 in double representation in little endian is

    00 00 00 00  00 4A 93 40
    

    A %d consumes a 32-bit integer, so a zero is printed. (As a test, you could printf("%d, %d\n", 1234.5f); You could get on output 0, 1083394560.)


    As for why the float is converted to double, as the prototype of printf is int printf(const char*, ...), from 6.5.2.2/7,

    The ellipsis notation in a function prototype declarator causes argument type conversion to stop after the last declared parameter. The default argument promotions are performed on trailing arguments.

    and from 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.

    (Thanks Alok for finding this out.)

    0 讨论(0)
  • 2020-11-30 23:29

    Since you tagged it with C++ as well, this code does the conversion as you probably expect:

    #include <iostream.h>
    
    int main() {
        float a = 1234.5f;
        std::cout << a << " " << (int)a << "\n";
        return 0;
    }
    

    Output:

    1234.5 1234
    
    0 讨论(0)
  • 2020-11-30 23:30

    It's because of the representation of a float in binary. The conversion to an integer leaves it with 0.

    0 讨论(0)
  • 2020-11-30 23:31

    You just need to use the appropriate format specifier (%d,%f,%s,etc.) with the relevant data type (int,float, string, etc.).

    0 讨论(0)
  • 2020-11-30 23:33

    hey it had to print something so it printed a 0. Remember in C 0 is everything else!

    0 讨论(0)
  • 2020-11-30 23:38

    You want %f not %d

    0 讨论(0)
提交回复
热议问题