• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Since when does 25/4 = 6.0?

 
Jake Miller
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I am following a book about teaching myself Java, and have this as an exercise:
Create an array to store five objects that are of class Integer, String, Boolean, Character, and Double. Displaye the elements.
Here is my program:



And here is the output:

7
Hello world!
false
x
6.0

How do I get the correct answer for the last element of the array?? I thought making it a double would make it an exact answer, i.e. 6.25 but all I can get as an output is 6.0. What's going on?
 
Campbell Ritchie
Sheriff
Pie
Posts: 47229
52
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, 25 / 4 has always made six. All you are getting from the double is adding a decimal point.


Go and find a table of precedences, and if you are lucky you will have this as the top row:

() . []

for round brackets (parentheses) dot for member access and square brackets for array access.
So, whatever is in the () brackets is executed and completed first. What you have in there is the integer division expression 25 / 4. You already know that integer division loses fractions, so you get 6. When you create a Double object from 6, it can't put the 0.25 bit back, because it has disappeared into cyber-limbo, but there is a 1 somewhere (also in cyber-limbo) which represents the remainder of the division, ie 6 % 4.

Try this little alteration:-

new Double(25.0 / 4) . . .
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The arithmetic is performed using int literals 25/4. Since int division always truncates, the result is 6, and this is the value that's widended to a double, 6.0.

To perform the arithmetic as doubles, replace one (or both) of the int literals with a double. For example, 25d/4.
 
Jake Miller
Ranch Hand
Posts: 43
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sweet, got it. Thanks
 
Consider Paul's rocket mass heater.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic