【发布时间】:2014-08-22 17:14:34
【问题描述】:
给定一个数字数组,我必须编写方法来查找平均值、中位数、众数等。我已经解决了其他所有问题,但是模式给了我一个地狱般的时间,不知道为什么。
数组为 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
【问题讨论】:
-
有不少地方出错了,尝试调试你的代码,单步调试,问题应该会很明显。
-
this answer 就是你要找的东西
标签: java