I have defined the following method which calculates the average of an array:
public int AverageOfArray (params int[] arr)
{
if (arr.Length > 0)
{
double avg = Sum(ints) / arr.Length;
return (int)avg;
}
return 0;
}
My requirement is that the average should be returned as an integer. When I tried to test this method using the int.MaxValue The unit test will fail. How can I make the test class pass?
UPDATED::-
public int Sum(params int[] arr)
{
int total = 0;
for (int n = 0; n < arr.Length; n++)
{
total += arr[n];
}
return total;
}
In the
Summethod, theintdata type is not sufficient to hold the sum ofint.MaxValue / 2andint.MaxValue / 2 + 4:Because the correct sum exceeds
int.MaxValue, it overflows into the sign bit, causing the result to be 232 less than the correct sum (see Two’s complement on Wikipedia for more information):The actual sum is wrong, so when you divide it by 2, you get the wrong average too. Garbage in, garbage out!
To fix this problem, change the return type of
Sumtolong, and change the type of thetotalvariable tolongas well:Now the
Summethod returns the correct sum:int.MaxValue + 3is less thanlong.MaxValue, so no overflow occurs.