如何使用C++容器查找中值?[duplicate]

bvuwiixz  于 2022-12-15  发布在  其他
关注(0)|答案(1)|浏览(92)

此问题在此处已有答案

What is the right approach when using STL container for median calculation?(10个答案)
4天前关闭。
我创建了一个程序,它要求输入数字,直到给出0,然后打印出 averagemediandescending,但是,我不知道如何得到 median,我试过了,得到了某种类型的结果,但是程序给出了错误的数字作为 median
输入:1 2 3 4 5 6 7 8 9 10 0(数字仅为示例)
预期产出:

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

这是我的尝试:

#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;
}
iqih9akk

iqih9akk1#

#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;
}

相关问题