Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding an Integer to a float not working as expected

Tags:

c

I know the following will not print 2.9 or 3. I can correct it but really want to understand what is internally happening so it is printing:

858993459

How does this number come ?

I am running this under windows 32 bit

int main()
{
    double f = 1.9; 
    int t = 1;

    printf("%d\n", t+f); 

    return 0; 
}

Update

Simply believing that this would be "undefined behavior" was not possible for me, so I thought of investigating it further. I found this answer exactly what I wanted to understand.

like image 597
user3891236 Avatar asked Mar 14 '26 03:03

user3891236


1 Answers

As others have already mentioned, this is undefined behaviour. But by taking some assumptions about the machine architecture, one can answer why it is printing these numbers:

Using IEEE 754 64-bit format to represent doubles values, the value of 2.9 is the a stored as 0x4007333333333333.

In a Little-Endian machine, the %d specifier will read the lower 4 bytes of that value, which are 0x33333333, which equals 858.993.459

like image 193
king_nak Avatar answered Mar 16 '26 16:03

king_nak



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!