0
What is the output of the following code? System.out.println (5/2%5)
the answer is two, but I'm not sure why. I keep getting this wrong in challenges. leave a like?
6 Réponses
+ 11
I don't think that there's a precedence of either division over modulo or the other way around. There are specific ways to interpret the expressions when both operators are on equal precedence.
That said, the basic explanation to the output would be:
5/2%5
2%5
2
// m mod n wherein m < n will return m.
// this is true for both C++ and Java.
+ 3
Ok, I searched the internet, if there's the same precedence you solve from the left to the right.
+ 1
0
No. Division takes higher precedence over modulo, so 5/2 = 2,
2 % 5 = 2 ( --> 2/5 = 0)
0
The confusing thing of that code is that the results of both ways are equal.
- 1
Modulo takes precedence over division, so first 2%5 is evaluated, which returns 2. This is because 5 doesn't go into 2 at all, so you have a remainder of 2. Then, 5/2 returns the int 2, not the float 2.5, because both the numerator and denominator are integers.