我必须创建要使用其他人拥有的主类来实现的类,并且出于某种原因我没有得到正确的输出,我不确定这个错误来自何处。
预期产出:
中位数= 44.5
平均值= 49.300
SD = 30.581
public class StatPackage {
int count;
double [] scores;
StatPackage() {
count = 0;
scores = new double[500];
}
public void insert (double value) {
if (count < 500){
scores[count] = value;
++ count;
}
}
public double Mean () {
double sum = 0;
//For loop for calculating average or mean
for(int i = 0; i < count; i++){
sum += (scores[i]);
}
double average = sum/count;
return average;
}
public double Median() {
int min;
int tmp;
int size;
for (int i = 0; i < count; i ++)
{
min = i;
for (int pos = i + 1; pos < count; pos ++)
if (scores [pos] < scores [min])
min = pos;
tmp = (int)scores [min];
scores [min] = scores [i];
scores [i] = tmp;
}
double median = 0;
if (count % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = (scores[((scores.length/2))]);
}
return median;
}
public double Variance () {
double variance = 0;
double sum = 0;
//For loop for getting the variance
for(int i = 0; i < count; i++){
sum += scores[i];
variance += scores[i] * scores[i];
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return (varianceFinal);
}
public double StdDev (double variance) {
double sum = 0;
for(int i = 0; i < count; i++){
sum += scores[i];
variance += scores[i] * scores[i];
}
double varianceFinal = ((variance/count)-(sum*sum)/(count*count));
return Math.sqrt(varianceFinal);
}
答案 0 :(得分:0)
您的Median()
方法存在问题。尝试更改
if (count % 2 == 0){
median = (scores[scores.length/2-1] + scores[scores.length/2])/2;
}
else {
median = scores[scores.length/2];
}
到
if (count % 2 == 0)
median = (scores[count/2] + scores[count/2 - 1])/2;
else
median = scores[count/2];
因为您有一个包含500个元素的固定大小的数组,所以您拥有的代码将返回位置249和250处的项目的平均值,如果您的数组中的值少于251,则该值将为0。
答案 1 :(得分:0)
在慈善/精神错乱中,我很快写了一个驱动程序,试图测试这个东西。
public static void main(String[] args)
{
StatsPackage sp = new StatsPackage();
for (int i = 0; i < 101; ++i) {
sp.insert(i);
}
System.out.println("count: " + sp.count);
System.out.println("mean: " + sp.Mean());
System.out.println("median: " + sp.Median());
System.out.println("variance: " + sp.Variance());
}
除了中位数没有计算正确的值(并且@BadCash可能有解决该问题的方法)之外,没有抛出ArrayOutOfBounds。
编辑:将更新作为@BadCash推荐给Median方法似乎解决了中位数没有给出正确答案。