Leroy J Brown

Ranch Hand

Posts: 71

posted 9 years ago

Ok,

I'm working on a project and I need to write a method that takes an input number, divides by three and then returns the number that is the closest mathematical integer

7 / 3 is 2.333~

So I don't understand why both

AND

are returning 2.0. Shouldn't Math.ceil return 3.0?

What am I missing please?

I'm working on a project and I need to write a method that takes an input number, divides by three and then returns the number that is the closest mathematical integer

*above*it. So a method that rounds up should be involved. I'm trying to test out the Math.ceil and Math.floor methods but I'm confused.7 / 3 is 2.333~

So I don't understand why both

AND

are returning 2.0. Shouldn't Math.ceil return 3.0?

What am I missing please?

posted 9 years ago

Not in Java, where 7 and 3 are each ints, and so the result of this operation is

To get a floating-point result, at least one of these values must be a floating-point type.

Originally posted by Tristan Rouse:

...

7 / 3 is 2.333~...

Not in Java, where 7 and 3 are each ints, and so the result of this operation is

**also**an int. (Truncated.)

To get a floating-point result, at least one of these values must be a floating-point type.

"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." *~Joe Strummer*

sscce.org

Robin Lane

Ranch Hand

Posts: 76

posted 9 years ago

"When you divide an int value by another int value, you get an int value. The computer doesn't round... (it) chops off any remainder... If you need a decimal answer, make either (or both) of the numbers you're dividing double values." Barry Burd, Author, Beginning Programming with Java for Dummies

I believe this means you must change your numbers to decimals, then divide, then round.

I believe this means you must change your numbers to decimals, then divide, then round.

Disclaimer: The author of this post makes no claims, implied or otherwise, as to her ability to understand anything but the simplest of answers. Further, the author of this post has no programming background whatsoever and has taken one Java Programming class which was 9 weeks long. She does want to learn, so please teach patiently.

Leroy J Brown

Ranch Hand

Posts: 71

posted 9 years ago

If you are using literals, the quickest way would be to just add a decimal to one of them...

7.0 / 3

Otherwise, defining a variable as type double would work.

(You probably don't want to "cast," because then you are boxing and unboxing Double objects for no reason.)

7.0 / 3

Otherwise, defining a variable as type double would work.

(You probably don't want to "cast," because then you are boxing and unboxing Double objects for no reason.)

*~Joe Strummer*

sscce.org