Nada Ghanem
Nada Ghanem

Reputation: 451

Median program through uva

This is my first time using online judge, I tried a simple program to become familiar with the environment.

Here is the question.

I solved it as the following, but get a wrong answer!

#include<stdio.h>
#include<math.h>
#include<iostream>

int main()
{
int t;
int n;
int num[10];
int i,j,temp;
int s;
int fmid;
std::cin >>t;
int iter=0;
while (iter<t)
{
std::cin>>n;
if (n!=-1){
for(i=0;i<n;i++)
std::cin>>num[i];

for( i=0;i<n-1;i++)

for(j=i+1;j<n;j++)
if(num[i]>num[j])
{temp=num[i];
num[i]=num[j];
num[j]=temp;
}

s=0;
if (n%2 ==0)
{
int mid=n/2-1;
int  midd=mid+1;

s=(num[mid]+num[midd])/2;
fmid=s;
}

else
{s=ceil(n/2);
fmid=num[s];}

std::cout<<fmid;
}
iter++;

}

return 0;

}

Any suggestion is much appreciated.

Thanks

Upvotes: 0

Views: 60

Answers (1)

yulonglong
yulonglong

Reputation: 86

I would read all the numbers, store them in an array, then sort the array using std::sort in <algorithm>

Please find my code below:

#include <stdio.h>
#include <math.h>
#include <iostream>
#include <algorithm>

int arr[10];

int main()
{
    int N;
    while ((std::cin >> N) && (N!=-1)){
        for(int i=0;i<N;i++) {
            std::cin >> arr[i];
        }
        std::sort(arr,arr+N);
        if(N%2 == 1){
            std::cout << arr[N/2] << std::endl;
        }
        else {
            double ans = ((double)arr[N/2] + (double)arr[(N/2)-1]) / 2.0;
            std::cout << ans << std::endl;
        }
    }

    return 0;
}

I hope it works for you.

May I know the problem number? I will try to submit there and give you an AC solution.

Upvotes: 1

Related Questions