Okay. I have been bashing my head against the wall for like 2 hours now trying to figure out why in the world double answer = 364/365;
is telling me that answer
is 0. Or any other combination of double
for that matter, its just truncating the decimal and I just don't know why.
When one of the operands to a division is a double and the other is an int, Java implicitly (i.e. behind your back) casts the int operand to a double. Thus, Java performs the real division 7.0 / 3.0.
In java, operations involving only integer types (int, long and so on) have integer results. This includes divisions. Both 30 and 4 are integer values, so if you try to divide them, integer division is used.
364/365 performs integer division (truncates the decimal).
Try double answer = 364.0/365;
to force it to perform floating point division.
Something like:
double days_in_year = 365;
double answer = 364/days_in_year;
would work as well, since one of the operands isn't an integer.
You're taking an int type (364) and dividing by another int type (365) - the answer is going to be an int. This is then stored in a double type answer. You could do the following:
double answer = 364d / 365d;
More info here:
http://mindprod.com/jgloss/division.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With