+ 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(); } }

19th Jan 2022, 9:52 PM
Chris
Chris - avatar
4 ответов
+ 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.
20th Jan 2022, 12:10 AM
Ani Jona 🕊
Ani Jona 🕊 - avatar
+ 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
19th Jan 2022, 10:04 PM
Ollie Q
Ollie Q - avatar
+ 1
Divide by 2.0 instead
19th Jan 2022, 10:43 PM
khabz01
khabz01 - avatar
+ 1
Ok, You guys gave good advice to solving the questions. Thank you.
20th Jan 2022, 1:25 AM
Chris
Chris - avatar