Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What's missing from my implementation of a function to find the middle number?

I’m supposed to implement a function that finds the middle number from three numbers given as input. All inputs are positive integers. I seem to not be treating a special case which is causing my program to fail some tests, but with a VERY small margin. I mean 1.46 standard deviation for 8bit pixel values, so the cases i’m missing ought to be very specific and rather few in between.

As i’m understanding this problem, there’s three possibilities for the numbers:

  1. They are all equal, so return either
  2. Two of them are equal, thus return the smaller one (larger one doesn’t work either)
  3. They’re all different, thus find the middle value

There either is a fourth case i’m not seeing or i’ve missed something for the above three. I can’t use libraries for sorting.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int middle(int a, int b, int c)
{
    if (a == b && b == c)
    {
        return c;
    }

    if ((a < b && b < c) || (c < b && b < a))
    {
        return b;
    }

    if ((b < a && a < c) || (c < a && a < c))
    {
        return a;
    }

    if ((a < c && c < b) || (b < c && c < a))
    {
        return c;
    }

    if (a == b || b == c || a == c)
    {
        if (a == b && a < c)
        {
            return c;
        }
        else
        {
            return a;
        }

        if (b == c && b < a)
        {
            return a;
        }
        else
        {
            return b;
        }

        if (a == c && a < b)
        {
            return b;
        }
        else
        {
            return c;
        }

    }

return c; // code sometimes reaches this point; it shouldn't
}

>Solution :

This case here:

if ((b < a && a < c) || (c < a && a < c))

is incorrect. It should be:

if ((b < a && a < c) || (c < a && a < b))

Further, in the

if (a == b || b == c || a == c)

Section, you have

if (...)
    return ...
else
    return ...

This will always return, and ignore the if statements following it.

That said, it would be a lot easier to sort the 3 values, then return b

if ( b < a ) {
    int t = a;
    a = b;
    b = t;
}
if ( c < b ) {
    int t = c;
    c = b;
    b = t;
}
if ( b < a ) {
    int t = a;
    a = b;
    b = t;
}
return b;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading