-3

I have created a program that asks for numbers until 0 is given. It then prints out the average, median, and descending, however, I don't know how to get the median. I have tried, and I get some type of result, but the program gives the wrong number as the median.

Input: 1 2 3 4 5 6 7 8 9 10 0 (Numbers are just an example)

Expected output:

Average : 5.5
Median : 5.5
Descending : 10 9 8 7 6 5 4 3 2 1

This is my attempt:

#include <iostream>
#include <vector>
#include<numeric>
#include "algorithm"

using namespace std;

int main() {
    vector<int> v;

    int n,i=0;
    double sum;

    cout << "Enter numbers(0 to stop inputting):"<<endl;
    cin>>n;

    while(n!=0){
        v.push_back(n);
        cin>>n;
    }

    for (const int& i : v) {
        sum = accumulate(v.begin(),v.end(),0);
    }

    double average = sum/v.size();
    cout<<"Average : "<<average<<endl;

    double Median = v[v.size()/2 -1];

    cout<<"Median : "<<Median<<endl;

    sort(v.begin(), v.end(), greater<int>());
    cout << "Descending : ";
    for (auto i : v)
        cout << i << " ";
    cout<<endl;
}
CreepyRaccoon
  • 826
  • 1
  • 9
  • 19
caitlyn
  • 1
  • 1

1 Answers1

1
#include <iostream>
#include <vector>
#include<numeric>
#include "algorithm"

using namespace std;

int main() {
    vector<int> v;

    int n,i=0;

    cout << "Enter numbers(0 to stop inputting):"<<endl;
    cin>>n;

    while(n!=0){
        v.push_back(n);
        cin>>n;
    }

    // no for!
    double sum = accumulate(v.begin(),v.end(),0);

    double average = sum/v.size();

    // sort BEFORE getting the middle element!
    sort(v.begin(), v.end(), greater<int>());

    double Median =
        v.empty() ? 0.0 :
        v.size() % 2 == 0 ? (v[v.size()/2 -1] + v[v.size()/2]) / 2.0 : // even count
        v[v.size()/2]; // odd count

    cout<<"Average : "<<average<<endl;
    cout<<"Median : "<<Median<<endl;
    cout << "Descending : ";
    for (auto i : v)
        cout << i << " ";
    cout<<endl;
}
Wyrzutek
  • 605
  • 1
  • 5
  • 13