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.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The reason is that the default type of integer literals in java is
int
and all the result of allint
based arithemetic is type casted back toint
. Hence though your answer is 0.997, when it is typecasted back it becomes 0:So you can do like this:
or
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:
More info here:
http://mindprod.com/jgloss/division.html
All the above answers are right, would just like to add that it is all about GIGO.
in above code double type implies only to answer variable and arithmetic expression has both operands of int type. So the output of the arithmetic expression is also int type which is then through auto up-casting to double type gives output 0.0, just like below examples:
the above code will give output Infinity as one of the operand is Floating-point number so through auto type-casting 0 is converted to 0.0 and the result is as per the Floating-point datatype.
whereas
will give java.lang.ArithmeticException: / by zero exception at runtime since both the operands are of datatype int and so the output is as per the Integer datatype irrespective of ans variable datatype being double.
You need do do double division. Right now Java is interpreting it as integer division and returning the truncated
int
.What you need is:
or
364/365 performs integer division (truncates the decimal).
Try
double answer = 364.0/365;
to force it to perform floating point division.Something like:
would work as well, since one of the operands isn't an integer.