Basic math operation in C#

I’m learning and have glanced over simple math operations in C#. However, a point that may be easy-peasy seems interesting that typically I know about division an integer by an another integer number is zero if first one is smaller than second one. So, I have looked at operator precedence in C# because maybe I have the wrong information about it. So, what about Console.WriteLine((1 + 1) / 2 * 3); Shouldn’t it give zero as a result? But it gives 3. Is there a point that I have wrong knowledge about C#?

@Edit: The problem is about my arithmetic. I think it should be 2 / 2 * 3 then 2 / 6 = 0 why division takes place before multiplication?

@Edit 2: The question can be closed. It is exactly about my wrong knowledge on precedence of operators. I had thought like a real math procedure in programming until now. I’m in shock. Advantages of the reading again and again and not skipping even if you supposed as I know the subject already

@Edit 3: After some time, I realized that there are some sorts of evaluation of math expressions called as like, PEMDAS, BODMAS, BEDMAS and BIDMAS. That’s why I got it wrong at first.

Answer

You should use the order of operations. order of operations
From this image, you can derive that you first need to add the two ones between parentheses. This will then be divided by 2. Finally, you multiply by three.

So (1+1)/2*3

Then 2/2 *3

Finally 1*3

As you can see multiply and divide gets executed from left to right. Multiplication isn’t executed before the division.

Leave a Reply

Your email address will not be published. Required fields are marked *