我需要帮助解决这个问题:
编写接受测试等级数组(0–100)的方法模式,并返回模式,即出现频率最高的等级。如果有多种模式,则返回最小的模式。
我的代码不工作:请帮助,谢谢!
public static int mode(int[] marks) {
int count = 0;
int count0 = 0;
int mostFrequent = marks[0];
for (int x = 0; x < marks.length; x++) {
if (marks[x] == mostFrequent) {
count++;
}
}
if (count>count0) {
count0 = count;
mostFrequent = marks[count];
}
return mostFrequent;
}
例如:
如果marks={1,2,4,6,1,1,1},它就工作了
如果marks={1,2,4,1,3,2,3,5,5},则不起作用
2条答案
按热度按时间disho6za1#
你需要计算所有数字的出现次数。请尝试以下操作。
cxfofazt2#
这应该可以做到:
注意:如果传递的数组为空,则最后一行将0设置为默认值。
如果要在这种情况下引发异常,请将其更改为: