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:
- They are all equal, so return either
- Two of them are equal, thus return the smaller one (larger one doesn't work either)
- 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.
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
}