简体   繁体   中英

Int can not hold the value of int.MaxValue

I have the following two methods:

public int Average (params int[] array)
{
    if (array.Length > 0)
    { 
        double avg = Sum(ints) / arr.Length;        
        return (int)avg;             
    }        
    return 0;
} 

public int Sum(params int[] array2)
{
    int total = 0;
    for (int n = 0; n < array2.Length; n++)
    {
        total += arr[n];
    }
    return total;
}

But for testing purposes I tried adding the int.MaxValue / 2 and int.MaxValue / 2 + 4. in the array. But why does the unit test fail, although the sum of the two values will be less than int.MaxValue ?

two values in the array[] :- int.MaxValue / 2 & int.MaxValue / 2 + 4.. but when i run the unit test it fails,, although the sum of the two values will be less than int.maxvalues?

No sir, the sum will be more than int.MaxValue :

(int.MaxValue / 2) + (int.MaxValue / 2 + 4) == int.MaxValue + 4 //...

You overflew the int max value.

Simple math: (x/2)+ (x/2 +4) == x+4

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM