Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java and division

 
Charles Saik
Greenhorn
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 117
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ok thank you very much!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic