Median program

This is a discussion on Median program within the C++ Programming forums, part of the General Programming Boards category; I've written this progarm which looks at 2 arrays then calls a function and returns the median of each array, ...

  1. #1
    Unregistered
    Guest

    Question Median program

    I've written this progarm which looks at 2 arrays then calls a function and returns the median of each array, but I think when I goto call the function the 2nd time it ignores it and just uses the value from the first time i called it....can someone help me out?

    #include <iostream.h>

    float Median(int *, int);

    void main(void)
    {
    int Odd[] = {1, 2, 3, 4, 5, 6, 7};
    int Even[] = {1, 2, 3, 4, 5, 6, 7, 8};

    cout << "Median using an odd array: " << Median(Odd, 7) << endl;
    cout << "Median using an even array: " << Median(Even, 8) << endl;
    }// void main(void)


    float Median(int *array, int size)
    {
    float First = 0, Last = size - 1;
    float evenanswer = 0, oddanswer = 0;
    int Middle;

    Middle = First + (Last - First) / 2;

    if ((Middle % 2) != 0)
    {
    oddanswer = array[Middle];
    return oddanswer;
    }
    else
    {
    evenanswer = (array[Middle] + array[Middle + 1]);
    evenanswer = evenanswer / 2;
    return evenanswer;
    }
    }// void Median(int *, int);

  2. #2
    Registered User
    Join Date
    Aug 2001
    Posts
    61
    Problem is that Middle is of type int so regardless whether you pass size as 7 or 8, meaning Last = 7 or Last = 6, Middle will turn out to be 3. Thus the expression Middle % 2 != 0 will evaluate to true in both cases (stick a little cout << "hello"; in the if branch and you'll see what i mean). Setting Last = size, rather than Last = size - 1, fixes the problem with distinguishing between an "even" array and an "odd" array, but i don't know if the calculations it yields is what you are looking for.

    by the way, is just me or is

    Middle = First + (Last - First) / 2;

    really just

    Middle = Last / 2;

    (algebraically no, but what i mean is since "First" initialized to 0).
    Last edited by greenRoom; 10-24-2001 at 10:10 PM.

  3. #3
    Unregistered
    Guest

    Talking thanks

    hey thx for the info, I used your suggestions as well as changed Median + 1 to Median - 1 and it works fine now.

  4. #4
    Unregistered
    Guest
    sorry meant to say Middle + 1 and Middle - 1

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Need help with a program, theres something in it for you
    By engstudent363 in forum C Programming
    Replies: 1
    Last Post: 02-29-2008, 01:41 PM
  2. Replies: 4
    Last Post: 02-21-2008, 10:39 AM
  3. Replies: 3
    Last Post: 03-04-2005, 02:46 PM
  4. My program, anyhelp
    By @licomb in forum C Programming
    Replies: 14
    Last Post: 08-14-2001, 11:04 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21