Answer the question
In order to leave comments, you need to log in
Sum of array elements greater than average - C++ How to solve?
Here, in fact, the problem itself:
You are given n natural numbers. Find the sum of numbers that are greater than the average. If there are no such numbers, then their sum is 0.
Input data Format
Number n comes first. Then n lines containing one natural number each.
Output data format
One number — the answer to the problem.
Examples
Input
5
1
2
3
4
5
Output
9
My code:
#include <iostream>
#include <ciso646>
using namespace std;
int main()
{
int n;
int A[10000] = {0};
cin >> n;
for(int i = 0; i < n; i++)
{
cin >> A[i];
}
bool is_sorted = false;
int tmp = 0;
while (not is_sorted)
{
is_sorted = true;
int i = 0;
while (i < n-1)
{
if (A[i] > A[i+1])
{
is_sorted = false;
tmp = A[i];
A[i] = A[i+1];
A[i+1] = tmp;
}
i++;
}
}
int middle = A[n / 2];
int sum = 0;
for(int j = n / 2 + 1; j < n; j++)
{
if (A[j] > middle)
sum += A[j];
}
cout << sum;
return 0;
}
Answer the question
In order to leave comments, you need to log in
Judging by the condition, it is necessary to consider the arithmetic mean, and you are looking for the median.
Instead of sorting, it is necessary to stupidly sum all the numbers and divide by their number (round down).
Well, do not forget at the end of the cycle to drive through all the elements and not from the middle.
The average is the sum of the numbers divided by their number. You have a median in your code. That's why it doesn't pass the test.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question