**New course!**Every coder should learn

**Generative AI!**

+ 1

# Help with math question

Here is the original code and the second one is my edit code... Im not sure why its not working. using System; public class MathUtils { public static double Average(int a, int b) { return a + b / 2; } public static void Main(string[] args) { Console.WriteLine(Average(2, 1)); } } EDITED CODE BELOW using System; public class MathUtils { public static double Average(int a, int b) { return (a + b) / 2; } public static void Main(string[] args) { Console.WriteLine(Average(2, 1)); Console.ReadKey(); } }

4 Answers

+ 2

Division that involves only integral data types (such as int) will be performed as integer division (quotient and remainder) and the result will be the quotient.
Due to division having higher precedence than addition, in the first case, 2 + 1 / 2, will calculate 1/2 as quotient 0 (remainder 1). Hence the result is 2+0=2.
In the second case, addition comes first because of the brackets. (2+1)/2 = 3/2 has quotient 1 (remainder 1). The result will be 1.
For floating point division, one of the numeric types involved must be a floation point type. That is why khabz01 suggested division by 2.0, which has a double type. The brackets need to stay, though :) To have addition first.

+ 1

Hi Brit
That is due to order of operations in mathematics which means the bracks will be caculated before being divided by two instead b divided by 2 plus a

+ 1

Divide by 2.0 instead

+ 1

Ok, You guys gave good advice to solving the questions. Thank you.