How is conversion of float/double to int handled in printf?

前端 未结 7 1824
逝去的感伤
逝去的感伤 2020-11-30 07:56

Consider this program

int main()
{
        float f = 11.22;
        double d = 44.55;
        int i,j;

        i = f;         //cast float to int
        j          


        
相关标签:
7条回答
  • 2020-11-30 08:55

    Jack's answer explains how to fix your problem. I'm going to explain why you're getting your unexpected results. Your code is equivalent to:

    float f = 11.22;
    double d = 44.55;
    int i,j,k,l;
    
    i = (int) f;
    j = (int) d;
    k = *(int *) &f;         //cast float to int
    l = *(int *) &d;         //cast double to int
    
    printf("i = %d, j = %d, f = %d, d = %d", i,j,k,l);
    

    The reason is that f and d are passed to printf as values, and then these values are interpreted as ints. This doesn't change the binary value, so the number displayed is the binary representation of a float or a double. The actual cast from float to int is much more complex in the generated assembly.

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