Welcome to Dream.In.Code
Getting C++ Help is Easy!

Join 136,460 C++ Programmers for FREE! Get instant access to thousands of C++ experts, tutorials, code snippets, and more! There are 1,767 people online right now. Registration is fast and FREE... Join Now!




Displaying the correct median in C

 
Reply to this topicStart new topic

Displaying the correct median in C

azuresonata
9 Aug, 2008 - 04:57 PM
Post #1

New D.I.C Head
*

Joined: 22 Jul, 2008
Posts: 9

This is a code that gets the median of an array of integers. The program is running however it only returns 0 as the median for both even and odd number of elements.

CODE


#include<stdio.h>
#include<stdlib.h>

int i;
int x[100];
int length;
int s;
int q;
int temp;
int go;
int n;


float get_median (int [], int);


int main(){

    int num,length, med;
    printf("How many numbers do you want?");
    scanf("%d",&length);

    printf("\nEnter your numbers:\n");
    scanf("%d",&num);
    for(i=1;i<length;i++)
            scanf("%d",&x[i]);
    for (i=1;i<=length-1;i++){
        for (s=1;s<=length-1;s++){
                if (x[i]>x[i+1]){
                temp=x[i];
                x[i]=x[i+1];
                temp=x[i+1];
                }
            else continue;
            }
        }

    printf("The median is :%.2f",get_median(x, length) );
    return 0;
}

float get_median(int a[],int b){

    int eq;

    for (n=1;n<b-1;n++)
    {
        for (i=1;i<b-1;i++)
        {
            if (a[i]>a[i+1])
            {
                eq=a[i];
                a[i]=a[i+1];
                a[i+1]= eq;
            }
        }
    }
    if (b%2==0)
    {
        return (float)(a[b/2]+a[b/2+1])/2;
    }
    else
    {
        return (float)a[b/2];
    }
}



anyone who knows how I could fix this?
User is offlineProfile CardPM
+Quote Post

KYA
RE: Displaying The Correct Median In C
9 Aug, 2008 - 05:33 PM
Post #2

#include <nerd.h>
Group Icon

Joined: 14 Sep, 2007
Posts: 4,883



Thanked: 99 times
Dream Kudos: 1200
My Contributions
The first thing I noticed was you have declared int length twice; once as a global variable and once again inside of main().

Also it seems like you are trying to sort the array twice. Is this the intended case?
User is online!Profile CardPM
+Quote Post

azuresonata
RE: Displaying The Correct Median In C
9 Aug, 2008 - 05:41 PM
Post #3

New D.I.C Head
*

Joined: 22 Jul, 2008
Posts: 9

Ah no. It was unintentional. I wrote that when I was doing trial and error to correct the code.

User is offlineProfile CardPM
+Quote Post

Reply to this topicStart new topic
Time is now: 12/2/08 04:14PM

Live C++ Help!

C++ Tutorials

Reference Sheets

C++ Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month