簡體   English   中英

如何在不使用 C++ 中的向量的情況下求解中位數?

[英]How to solve median without using vectors in C++?

我想編寫一個程序來查找排序數組的均值和中位數(以便我可以更快地完成數學作業)而不使用向量。 我在 HackerRank 中編寫了這個程序:

#include <bits/stdc++.h>
using namespace std;

int main() {
    int arr[2500],x;
    double sum, mean;
    cin>>x;

    //solving for mean
    for(int i = 0; i <= x; i++) {
        cin>>arr[i];
    }
    sort(arr, arr + x);
    sum = 0.0;
    for (int i = 0; i <= (x-1); i++)
    {
        sum += arr[i];
    }
    mean = sum/x;
    cout<<fixed<<setprecision(1)<<mean<<endl;


    //solving for median
    if (x%2==0)
    cout<<fixed<<setprecision(1)<<arr[x/2]<<endl;
    else 
    cout<<fixed<<setprecision(1)<<((arr[(x-1)/2] + arr[x/2])/2.0)<<endl;
    
    return 0;
}

輸入是:

10
64630 11735 14216 99233 14470 4978 73429 38120 51135 67060

預期的輸出是:

43900.6
44627.5

但我的輸出是:

43900.6
51135

我無法弄清楚問題所以請幫助🙏

if (x%2==0)
    cout<<fixed<<setprecision(1)<<arr[x/2]<<endl;
else 
    cout<<fixed<<setprecision(1)<<((arr[(x-1)/2] + arr[x/2])/2.0)<<endl;

如果x是奇數,則(x-1)/2x/2返回相同的值,因此(arr[(x-1)/2] + arr[x/2])/2.0僅相當於arr[x/2] 你需要使用

(arr[x/2] + arr[(x + 1)/2])/2.0

或者

(arr[x/2] + arr[x/2 + 1])/2.0

兩個問題:

奇/偶校驗相反。 如果項目數是偶數,則中間兩個數取平均值,如果是奇數,則中間數為中位數。

if (x%2==0)

應該是if (x%2!=0)if (x%2)你也可以交換ifelse的內容。

中間兩個指標的計算不正確。

((arr[(x-1)/2] + arr[x/2])/2.0)

應該

((arr[x / 2 - 1] + arr[x / 2]) / 2.0)

糾正這兩個問題后,輸出是預期的

43900.6
44627.5

更正代碼的在線示例

小問題:

for(int i = 0; i <= x; i++)

如果x == 10這將嘗試讀取 11 個數字。 它應該是i < x

for (int i = 0; i <= (x-1); i++)

這是正確的,但可以簡化為i < x

改變你的 if 條件。 x 是從 0 開始的數組長度。因此,如果數組的長度為 12,則 x 本質上為 11。

首先,輸入循環應該是

for(int i=0;i<x;i++) {
    cin>>arr[i];
}

中位數應該是

if (x%2 == 1)
    cout<<fixed<<setprecision(1)<<arr[x/2]<<endl;
else 
    cout<<fixed<<setprecision(1)<<((arr[(x-1)/2] + arr[x/2])/2.0)<<endl;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM