Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

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?

like image 1000
user12018058 Avatar asked Dec 10 '22 02:12

user12018058


2 Answers

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.

like image 69
Pasan Chamikara Avatar answered Feb 16 '23 00:02

Pasan Chamikara


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.

like image 38
Luaan Avatar answered Feb 15 '23 23:02

Luaan