Reputation: 71
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?
Upvotes: 4
Views: 349
Reputation: 1
try this. This is just basic mathematical grouping issue. (a.Max() + (a.Sum() % 10)) You can understand on this based on https://learn.microsoft.com/en-us/cpp/c-language/precedence-and-order-of-evaluation?view=vs-2019.
Upvotes: 0
Reputation: 305
The answer should be 11 because :
int[] a = {5, 6, 10}
int n = a.Max() + a.Sum() % 10;
n = 10 + 21 % 10 ;
n = 10 + 1;
n = 11;
if you want it to be 1 you should use proper parenthesis , only then it will prioritize the calculations:
int[] a = {5, 6, 10}
int n = (a.Max() + a.Sum()) % 10;
n = (10 + 21) % 10 ;
n = 31 % 10 ;
n = 1;
Upvotes: 2
Reputation: 63722
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.
Upvotes: 5
Reputation: 11
you should Use BOD MAS Rule here. max value = 10, sum of all the numbers = 21, and then calculate mode. so the solution will be :
10 + 21 % 10
10 + 1 = 11
according to the BOD MAS Rule.
Upvotes: 0
Reputation: 755
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.
Upvotes: 6
Reputation: 13006
try this. This is just basic mathematical grouping issue.
multiplication and division will be evaluated last after + or -
int[] a = {5, 6, 10};
int n = (a.Max() + a.Sum()) % 10;
Console.Write(n);
Upvotes: 0