You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用C++容器正确计算中位数?现有程序结果错误求修正

问题:中位数计算错误的程序修正

问题描述

我编写了一个程序,功能是接收数字输入直到输入0停止,随后输出平均值、中位数和降序排列的数字,但中位数计算结果始终不正确。

输入示例

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

问题分析与修正

核心问题

  1. 计算中位数前未排序:中位数的计算必须基于升序排列的数组,原代码直接使用未排序的数组取值,结果必然错误。
  2. 未处理数组长度奇偶情况:
    • 数组长度为奇数时,中位数是中间位置的元素
    • 数组长度为偶数时,中位数是中间两个元素的平均值
  3. sum计算冗余:原代码在循环中重复调用accumulate,实际上只需调用一次即可。

修正后的代码

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

using namespace std;

int main() {
    vector<int> v;

    int n;
    double sum;

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

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

    // 计算总和与平均值,移除冗余循环
    sum = accumulate(v.begin(), v.end(), 0);
    double average = sum / v.size();
    cout << "Average : " << average << endl;

    // 先对数组升序排序,用于计算中位数
    sort(v.begin(), v.end());
    double median;
    int size = v.size();
    if (size % 2 == 1) {
        // 奇数长度,取中间元素
        median = v[size / 2];
    } else {
        // 偶数长度,取中间两个元素的平均值
        median = (v[size / 2 - 1] + v[size / 2]) / 2.0;
    }
    cout << "Median : " << median << endl;

    // 重新排序为降序输出
    sort(v.begin(), v.end(), greater<int>());
    cout << "Descending : ";
    for (auto num : v) {
        cout << num << " ";
    }
    cout << endl;

    return 0;
}

关键修改点

  • 移除了计算sum的冗余循环,直接单次调用accumulate
  • 在计算中位数前,先对数组进行升序排序
  • 增加了数组长度奇偶性判断,分别处理中位数计算逻辑
  • 变量命名更规范(如Median改为小写median,符合C++命名习惯)

内容的提问来源于stack exchange,提问作者caitlyn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 12:30:53