Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to round integer towards negative infinity

I’m having some problems with this exercise.
Basically, I need to calculate and return a number using this formula: (input - 10) / 2

I also have to round the result down, and because results can be negative numbers, I have to round them towards negative infinity and not towards 0. The function has to return an Integer.

This is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int modifier(int input) {
    return (int) Math.floor((input - 10) / 2);
}

I’ve also tried other solutions, like BigDecimal.

An example is:

input = 3

so => 3 - 10 = -7 / 2 = -3.5 = -4

It keeps giving me -3 instead.

I don’t really understand what I’m doing wrong, it should be an easy task but apparently it’s not.

>Solution :

The problem is that you are performing integer division.

If you change your code to

return (int) Math.floor((input - 10) / 2.0);

It will work as expected.

Check also this answer for a deeper understand: Integer division: How do you produce a double?

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading