Bohn Bohn - 1 month ago 6
C# Question

Function to calculate average of two integers

I wrote this:

public static decimal Average(int a, int b)
{
return (a + b) / 2;
}

public static void Main(string[] args)
{
Console.WriteLine(Average(2, 1));
Console.ReadKey();
}


but it returns
1
. But it should return
1.5

How can I fix it to return 1.5 ?

Answer

Missing typecasting on the Average function

public static decimal Average(int a, int b)
{
    return (decimal)(a + b) / 2;
}

public static void Main(string[] args)
{
    Console.WriteLine(Average(2, 1));

}