views:

160

answers:

4

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. Please help!!!

+8  A: 

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.

Sapph
Hey thanks. That was really simple, but now I know!
Jeff
Happy to help. :)
Sapph
+2  A: 

You need do do double division. Right now Java is interpreting it as integer division and returning the truncated int.

What you need is:

double answer = 364 / 365.0;

or

double answer = 364 / (double) 365; 
jjnguy
+4  A: 

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

Jon
+1 for using the d suffix, which is much nicer (IMHO) than adding a .0 to the end or using an explicit cast, as all the other answers suggest.
Cowan
A: 

The reason is that the default type of integer literals in java is int and all the result of all int based arithemetic is type casted back to int. Hence though your answer is 0.997, when it is typecasted back it becomes 0:

(int)0.997  = 0

So you can do like this:

364.0/365.0

or

((float)364)/365
Suraj Chandran