我正在尝试完成“加速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;
}发布于 2017-05-04 20:49:44
首先,您的代码有点混乱,难以阅读。如果您使用现代的C++编译器,您就不需要那种愚蠢的typedef。您可以使用类型扣减:
auto size = set.size();使用size % 2 == 0作为布尔值是一种口头禅,它通常被写成(size % 2) --为了清晰起见,只使用该表达式一次可能是谨慎的
有三种确定四分位数的方法,它们给出了不同的答案,您的代码不匹配其中的两种方法(因为每个方法都检查数据集中项目的实际计数)--它匹配"1-Var Stats“方法,该方法由于错误而不返回您需要的值。
- If there are an odd number of data points in the original ordered data set, **do not include** the median (the central value in the ordered list) in either half.
- If there are an even number of data points in the original ordered data set, split this data set exactly in half.
我想,你希望图基的铰链(中间铰链)有一个?
- If there are an odd number of data points in the original ordered data set, **include** the median (the central value in the ordered list) in both halves.
- If there are an even number of data points in the original ordered data set, split this data set exactly in half.
如果关于统计的书太远了,就有用wiki和应用数学stackexchange描述的算法。
研究你的代码行为:你计算“中间”只是通过划分数组的大小,如果你取上或下的“中间”值,就不能控制。为什么?理论上,在不均匀计数的情况下,如果四舍五入,你总是会取上值,但实际上你只取下一个,因为你是用整数运算的,除法的结果会被截断。对于大小= 11,您的中间值为5。而“上”索引会发生什么情况呢?
auto upper = size - mid; //? upper = 6 That's not right应该是
auto upper = (size + mid)/2;这将为第一种方法提供适当的答案: 60 75 90
https://stackoverflow.com/questions/43792127
复制相似问题