Wait, What does it Print out?

What does the following Java code print out:

int i = 1234567890;
float f = i;
System.out.println((int)f - i);


The answer is 46.

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

Ivan Koswara
Jul 4, 2014

The primitive type float is a single-precision floating-point format . According to the IEEE 754 standard, the mantissa holds 24 significant bits. However, 1234567890 in binary is 1001001100101100000001011010010 , too long (31 bits), and thus must be rounded into a scientific format-like 1.0010011001011000000011 0 2 2 30 1.00100110010110000000110_2 \cdot 2^{30} . When cast back to an int , the above truncation gives 1234567936 , and thus (int)f - i = 1234567936 - 1234567890 which is 46 \boxed{46} .

Daniel Liu
Jul 3, 2014

The number is too big to store in a float primitive type. Some rounding occurs (this can be figured out by converting 1234567890 into binary and truncating some digits I think) and the end result is 46 46 .

Shared to me by @Zong Zhang .

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...