Jahaha
Jahaha

Reputation: 29

why doesn't my sorting code work?

Write the definition of a function minMax that has five parameters . The first three parameters are integers . The last two are set by the function to the largest and smallest of the values of the first three parameters . The function does not return a value .

The function can be used as follows:

int a=31, b=5, c=19 big, small; minMax(a,b,c,&big,&small); /* big is now 31 / / small is now 5 */

void minMax (int a, int b, int c, int *big, int *small) {
    if (a > b && a > c) 
        *big = a;
    else if (b>a && b>c)
            *big = b;
    else if (c>a && c>b)
            *big = c;

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

Remarks: ⇒ Your function did not change the value of small. Make sure you are dereferencing it in your function.

Common Errors: Make sure your if/else statements are correct. Make sure you have semicolons at the end of each statement. Make sure you are assigning the correct values to big and small.

Upvotes: 0

Views: 102

Answers (2)

If the 3 numbers a, b and c are all different, your code should work fine. But if 2 (or even all 3) values are the same, you will get an error, because you are always checking for "strictly greater than" and "strictly less than", that is, you are using > and < instead of >= and <=. Try it with a=31, B=31, C=31 and you will see that you will neither assign a value to *big nor to *small.

Upvotes: 1

Robinson
Robinson

Reputation: 10122

How about this:

void minMax(int x, int y, int z, int * big, int * small) 
{
    *big = x;   

    if (y > *big) 
    {
        *big = y;
    }

    if (z > *big) 
    {
        *big = z;
    }

    *small = x;

    if (y < *small)
    {
        *small = y;
    }

    if (z < *small)
    {
        *small = z;
    }
}

Upvotes: 0

Related Questions