user12018058
user12018058

Reputation: 71

Why do I get the wrong result when evaluating an expression?

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

Answers (6)

swapnil bhujbal
swapnil bhujbal

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

Waqas Amjad
Waqas Amjad

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

Luaan
Luaan

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:

  1. Get a.Max()
  2. Get a.Sum() % 10
  3. Add them together

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:

  1. Get a.Max()
  2. Get a.Sum()
  3. Add them together
  4. Take the remainder after division by 10

The result of that is 1.

Upvotes: 5

Rahul t.
Rahul t.

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

Pasan Chamikara
Pasan Chamikara

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.

enter image description here

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

Ed Bangga
Ed Bangga

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

Related Questions