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:
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?