int[] a = {5, 6, 10}
int n = a.Max() + a.Sum() % 10;
Console.Write(n);
The code prints out 11, but I would expect 1 because 31 % 10 = 1. Can anybody explain why the code above gives a different answer?
The problem is regards to operator precedence .
While the expression int n = a.Max() + a.Sum() % 10;
is evaluated,
based on operator precendence , you can see that additive operations come after multiplicative.
In order to fix this, one solution is to use brackets as belows.
int n = (a.Max() + a.Sum()) % 10;
If you can see as per in the operator precedence, using brackets make sure to recognize the content within as an expression and evaluates it first.
You can understand on this based on https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=vs-2019.
As a matter of fact operator precedence of all the c based languages are similar.
The problem you're facing is due to operator precedence. %
has precedence over +
, so what you're actually doing with your expression is:
a.Max()
a.Sum() % 10
So the result is 10 + 1, which is 11.
If you want to take the remainder of the addition, rather than just the a.Sum()
, you need to use parentheses: (a.Max() + a.Sum()) % 10
. This changes the evaluation to:
a.Max()
a.Sum()
The result of that is 1.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With