Reputation: 2423
I wrote a simple piece of code - ceil1
. Since it failed my test cases after rewriting same code - ceil
worked.
public class Test {
public static void main(String args[]){
System.out.println(ceil(3, 2)); //getting 2
System.out.println(ceil1(3, 2)); //getting 1
}
public static int ceil(int dividend, int divisor){
int a = dividend/divisor;
int b = dividend%divisor == 0 ? 0:1;
return a+b;
}
public static int ceil1(int dividend, int divisor){
return dividend/divisor + dividend%divisor == 0 ? 0:1;
}}
I can't put my finger on what is difference between these two? Possibly intermediate calculation/operator precedence causing this haywire.
Upvotes: 1
Views: 594
Reputation: 140299
Irrespective of the precedence issue, your code produces incorrect answers.
For example, ceil(-5, 3)
returns 0, whereas Math,ceil(-5.0 / 3.0)
returns -1 (the "un-ceiled" value is -1.666667
).
You will get the correct answer if you use a simpler approach:
(dividend + divisor - 1) / divisor
Upvotes: 1
Reputation: 14999
All of /
, +
, %
have a higher precedence than ==
, hence
dividend/divisor + dividend%divisor == 0 ? 0:1
is equivalent to
(dividend/divisor + dividend%divisor) == 0 ? 0:1
So you will always get either 0 or 1 from this.
Upvotes: 1
Reputation: 310983
The addition (+
) operator has a higher precedence than the ternary (?
) operator. You can surround that expression with parenthesis to get the behavior you want:
public static int ceil1(int dividend, int divisor){
return dividend/divisor + (dividend%divisor == 0 ? 0:1);
}
Upvotes: 1
Reputation: 393771
In
return dividend/divisor + dividend%divisor == 0 ? 0:1;
The addition of
dividend/divisor + dividend%divisor
is performed and then the result is compared to 0.
You want:
return dividend/divisor + (dividend%divisor == 0 ? 0:1);
or
return dividend/divisor + (dividend%divisor == 0) ? 0:1;
In order that only dividend%divisor
will be compared to 0
.
Upvotes: 3