Average function in C

C Program: Average Function




#include <limits.h>

int avg(int a, int b)
{
    int max = INT_MAX;
    int min = INT_MIN;
    int hmax = max / 2;
    int hmin = min / 2;

    if ((a == max) && (b == max)) {
        return max;
    }
    else if ((a == min) && (b == min)) {
        return min;
    }
    else if (a == b) {
        return a;
    }

    // 2 conditions of failure left to cover
    // 1 A == max , B > hmax
    // 2 B == max , A > hmax
    // Fuck
    if(a > hmax ) {
        if (b > hmax) {
            return hmax + (((a - hmax) + (b - hmax)) / 2);
        }
        else if (b > 0) {
            return (a / 2) + (b / 2);
        }
        else {
            return ((a + b) / 2);
        }
    }
    else if (a < hmin) {
        if (b < hmin) {
            return hmin + (((a - hmin) + (b - hmin)) / 2);
        }
        else if (b < 0) {
            return (a / 2) + (b / 2);
        }
        else {
            return ((a + b) / 2);
        }
    }
    else {
        return ((a + b) / 2);
    }
}


Learn More :