【发布时间】:2017-02-05 12:03:05
【问题描述】:
我是 java 新手,我有一个家庭作业,我需要找到一个数组的平均值、中位数和众数。出于某种原因,我的代码没有给出正确的答案。
这是我提供的用于创建数组的代码:
public static void main(String[] args) {
int[] test01 = new int[]{2,2,2,2,2};
int[] test01Results = new int[]{2,2,2,2};
int[] test02 = new int[]{1,2,1,3,5,6,6,1,2,2,2,99,100};
int[] test02Results = new int[]{2,2,17,100};
int[] test03 = new int[]{100,200,300,400,300};
int[] test03Results = new int[]{300,300,260,400};
int[] test04 = new int[]{100};
int[] test04Results = new int[]{100,100,100,100};
int[] test05 = new int[]{100,1};
int[] test05Results = new int[]{1,100,50,100};
这是我想出的尝试计算众数的方法:
public int mode() {
int result = 0;
// Add your code here
int repeatAmount = 0; //the amount of repeats accumulating for the current i
int highestRepeat=0; // the highest number of repeats so far
for (int i=0; i<numberArray.length; i++) {
for (int j=i; j<numberArray.length; j++) {
if (i != j && numberArray[i] == numberArray[j]) {
repeatAmount++;
if (repeatAmount>highestRepeat) {
result=numberArray[i];
}
repeatAmount = highestRepeat;
}
repeatAmount=0; // resets repeat Count for next comparison
}
}
return result;
}
我在测试 1、2 和 3 中得到了正确的结果,但在测试 4 和 5 中得到了错误的结果。有人知道我做错了什么吗?
谢谢!
【问题讨论】:
-
他做了功课,但面临一些问题@Shadetheartist
-
@rish 可以理解,但 prabod 能够在一分钟内找到可能的重复项,因此这表明 OP 在发布问题之前没有花足够的精力研究他的问题。
-
我确实看到了那个问题,但发现它使用了哈希图,因为我不知道那是什么,所以我决定发布我自己的问题。 @Shadetheartist
-
他的问题非常具体。他想知道为什么他在最后 2 次测试中得到错误的结果。而已。不要认为他需要整个代码!