我必须编写方法来查找给定数字数组的平均值,中位数,模式等。我已经完成了所有其他的工作,但是模式给了我很多时间,不知道为什么。查找数组方法(java)
该阵列是22,26,45,46,49,55,57,63,63,65,66,67,67,68,68,69,70,71,72,73,75,76 ,76,77,77,78,78,78,79,82,82,83,84,85,87,88,88,89,89,91,92,98,99
它正在返回22当答案应该是78
这里是我的代码:
public static int mode(int[] array){
int[] countArray = new int[101];
//counts each number
for(int i = 0; i < array.length; i++){
countArray[array[i]]++;
}// end for loop
int mode = array[0], modeIndex = 0;
//finds which number occurs the most
System.out.println(Arrays.toString(countArray));
for(int i = 1; i < array.length; i++){
if(countArray[i] > mode){
mode = countArray[i];
modeIndex = i;
System.out.println(mode + " " + modeIndex);
}// end if
}// end for loop
return modeIndex;
}// end method mode
有不少东西错了,试着调试你的代码,逐步完成它,问题应该变得明显。 – Taylor
[这个答案](http://stackoverflow.com/a/15725452/2817802)是你正在寻找的 – Baby