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.
CodePudding user response:
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?
CodePudding user response:
You are always getting -3
because (input - 10) / 2
was always returning -3
, which doesn't get any effect after using floor()
.
input - 10
is integer here and after dividing by another integer (2
in this case), it will return another integer value.
So, to overcome this problem, either cast the dividend/divisor to double before using floor()
:
int modifier(int input) {
return (int) Math.floor((double)(input - 10) / 2);
}
Or, more simply use a decimal value as divisor (e.g. 2.0
):
int modifier(int input) {
return (int) Math.floor(input - 10 / 2.0);
}
CodePudding user response:
Your solution needs to evaluate the result of the intermediate operation to determine if the integer is negative or not. If positive, you need to round down and up if it is negative. This is to round towards negative and positive infinities respectively.
int modifier(int input) {
double result = (input - 10) / 2.0;
if (result > 0) {
return (int) Math.ceil(result);
}
return (int) Math.floor(result);
}
Running these cases
System.out.println(modifier(1)); // -4.5
System.out.println(modifier(2)); // -4.0
System.out.println(modifier(3)); // -3.5
System.out.println(modifier(4)); // -3.0
System.out.println(modifier(21)); // 5.5
Return the following:
-5
-4
-4
-3
6
If only rounding towards negative infinity is required, simply remove the condition to check if the intermediate result is positive.
static int modifier(int input) {
double result = (input - 10) / 2.0;
return (int) Math.floor(result);
}