0

Why does this print out -1.0?

double num = Integer.MIN_VALUE + Integer.MAX_VALUE; System.out.println(num);

24th Dec 2017, 9:59 PM
PurePureMilk
2 Answers
+ 1
Because there is one more negative number than positive. And you explicitly wanted a double.
24th Dec 2017, 10:03 PM
1of3
1of3 - avatar
+ 1
@1of3 is correct. Try: public class Program { public static void main(String[] args) { //Integer.MIN_VALUE double nummax = Integer.MAX_VALUE; double nummin = Integer.MIN_VALUE; //double numt =Integer.MIN_VALUE +Integer.MAX_VALUE; double num = nummin + nummax; System.out.println(nummax); System.out.println(nummin); //System.out.println(numt); System.out.println(num); } } Google floating pt vs integer. Basically put: the computer is reading a certain number of 0’s and 1’s differently. Integers are direct. And from what I can see it is treating the integer memory as signed. Hence -num is the binary opposite of positive number. e.g. if there is a 4 bit integer max would look like: 0111 = 7 Min would be: 1000 = -7 and not 8 or 1111 = 15 or -7 as you might expect Floating point has to interpret it with perceived precision, since there is only a certain amount of numbers we can store with fix amount of memory. Hence the discrepancy that you see.
25th Dec 2017, 3:47 AM
H Chiang