int k = 50; int a = (k/5) * k + (k/2) % 2; System.out.print(a); // it prints out 501 // say that I calculated (k/5)*k+(k/2) already together which is 525 so int a = 525 % 2; System.out.print(a); // it prints out 1 Why is the first answer different than my second one?
Math equation with % (modulo) clarification help
You must be signed in to leave a comment
11 January 2020, 03:24
It is because of the precedence of the operations. On the right side of your assignment stays this expression: (k/5) * k + (k/2) % 2; So you used the following operators in this: (), / * %, and +. The precedence is in this order that I wrote. So your program will count the values in the parantheses first, k/5 (which is 10) and k/2 (which is 25). Next, it sees a * and a %. These are on the same stage in the preference list, so the next movements are: 10*50 (which is 500) and 25%2 (which is 1). Last, the program notices a + sign between these values, so it adds them: 500 + 1 = 501. What you wrote for the second time ("// say that I calculated (k/5)*k+(k/2) already together which is 525 so" [525 % 2 = 1]) is wrong. It would be true, if you have written this: ((k/5)*k+(k/2)) % 2. Here is a preference table that Java uses, I suggest you to study it, it would be helpful. http://www.cs.bilkent.edu.tr/~guvenir/courses/CS101/op_precedence.html The upper the used operator is in this table, the higher its preference, so the program will fulfil this operation than the lower ones. I hope I could help you. BR, András
11 January 2020, 03:29
* fulfil this operation EARLIER than the lower ones // sorry, I missed a word