c++ - Median program through uva -
this first time using online judge, tried simple program become familiar environment.
here question.
i solved following, 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 appreciated.
thanks
i read numbers, store them in array, sort array using std::sort
in <algorithm>
please find 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 works you.
may know problem number? try submit there , give ac solution.
Comments
Post a Comment