my dog learned polymorphism*
The moose likes Beginning Java and the fly likes java and division Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "java and division" Watch "java and division" New topic
Author

java and division

Charles Saik
Greenhorn

Joined: Sep 07, 2007
Posts: 8
Can anyone tell me why this gives an answer of 0.0? I assume it has to do with rounding. What can I do to get it to come out to the right answer?



Thanks!
Adam Nace
Ranch Hand

Joined: Jul 17, 2006
Posts: 117
It gives you zero because you are performing integer division. When the operand on the left of the division AND the operand on the right of the division are both integers, java will perform integer division, EVEN if the result is being assigned to a floating point variable.

Integer division means that it does the division, and then truncates the decimal places (i.e. removes the entire fractional part of the number), so that the result is still an integer.

Sooooo...

If you want to perform floating point division, you need to convert at least one of the operands to a floating point number. The 100 looks like a good place to start.

Change the 100 (which is the integer 100) to 100.0 (which is a double precision floating point number 100), and your code should work correctly.

- Adam
Charles Saik
Greenhorn

Joined: Sep 07, 2007
Posts: 8
Ok thank you very much!
 
GeeCON Prague 2014
 
subject: java and division