我正在嘗試完成「加速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;
}
上四分位數,最精確的四分之一?我只知道第一,第二和第三四分位數,任何單個項目都可能「處於上四分位數」。 – Swift
我指的是第一個四分位數爲「下」,第三個爲「上」。 –