2017-05-04 149 views
0

我正在嘗試完成「加速C++」練習3-2。我已經測試過了,下四分位數和中位數的計算是正確的,但上四分位數不是。計算給定數字列表的四分位數

例如,假設輸入 「50,60,70,80,90,100」,將輸出的四分位數爲60,75,和80。

我有兩個問題我希望處理:

1)上四分位數,在這種情況下,應該是90. 2)如何讓我的程序顯示我的數字的浮點數或雙精度數?較低的一個更精確的四分位數是62.5,而不是60.

/* Write a program to compute and print the quartiles(quarter of the 
* numbers with the largest values) of a set of integers 
* The first quartile (Q1) is defined as the middle number between the smallest number and the median of the data set. 
* The second quartile (Q2) is the median of the data. 
* The third quartile (Q3) is the middle value between the median and the highest value of the data set.*/ 

#include <algorithm> 
#include <iomanip> 
#include <ios> 
#include <iostream> 
#include <string> 
#include <vector> 

using std::vector; 
using std::endl; 
using std::cout; 
using std::cin; 

int main() { 
    double x = 0; 
    double median, lowerQt, upperQt; 
    median = lowerQt = upperQt = 0; 
    vector<double> set; 
    typedef vector<double>::size_type vec_sz; 

    cout << "Enter integers followed by EOF: "; 

    while(cin >> x) 
     set.push_back(x); 

    vec_sz size = set.size(); 
    if(size == 0) { 
     cout << "invalid" << endl; 
     return 1; 
    } 

    vec_sz mid = size/2; 
    vec_sz lower = mid/2; 
    vec_sz upper = size - mid; 

    sort(set.begin(), set.end()); 

    median = size % 2 == 0 ? (set[mid] + set[mid - 1])/2 : set[mid]; 
    lowerQt = mid % 2 == 0 ? (set[lower] + set[lower - 1])/2 : set[lower]; 
    upperQt = mid % 2 == 0 ? (set[upper] + set[upper - 1])/2 : set[upper]; 

    cout << lowerQt << endl << median << endl << upperQt; 
} 
+0

上四分位數,最精確的四分之一?我只知道第一,第二和第三四分位數,任何單個項目都可能「處於上四分位數」。 – Swift

+0

我指的是第一個四分位數爲「下」,第三個爲「上」。 –

回答

1

對於初學者來說,你的代碼有點雜亂,難以閱讀。如果您使用現代C++編譯器,則不需要那種愚蠢的typedef。您可以使用類型推演:

auto size = set.size(); 

使用size % 2 == 0爲布爾拗口,它通常寫爲(size % 2)不過還是謹慎爲清楚起見使用表達式只有一次

有三種方法來確定位數和他們給出了不同的答案,你的代碼不匹配其中的兩個(因爲每個方法都會檢查數據集中的實際項目數).Code it它與「1-Var Stats」方法相匹配,不會返回所需的值由於錯誤。

  1. 使用中位數將有序數據集分成兩半。

    • 如果在原來的奇數個數據點的有序數據集,不包括在上下半場的中位數(排序列表中的中間值)。

    • 如果原始有序數據集中有偶數個數據點,則將該數據集精確地分成兩半。

  2. 下四分位數值是數據下半部分的中位數。上四分位數值是數據上半部分的中位數。

我想,你期望Tukey的鉸鏈(midhinge)一個嗎?

  1. 使用中位數將有序數據集分成兩半。

    • 如果在原來的奇數數據點的有序數據集,包括在兩半中值(在有序列表中中央值)。
    • 如果原始有序數據集中有偶數個數據點,則將該數據集精確地分成兩半。
  2. 下四分位數值是數據下半部分的中位數。上四分位數值是數據上半部分的中位數。

如果關於統計的書太遠了,那麼在wiki和應用數學stackexchange中描述的算法。

研究你的代碼行爲:如果你採用上或下「中」值,你只需通過分割數組大小來計算「mid」。爲什麼?理論上,如果計數不均勻,則總是會取上限值,如果四捨五入,但實際上只取較低值,因爲您使用整數值進行操作,其中除法結果將被截斷。對於大小= 11,你的中間會是5.而「上」索引會發生什麼?

auto upper = size - mid; //? upper = 6 That's not right 

應該

auto upper = (size + mid)/2; 

這將給予適當的答案第一種方法:60 75 90