Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/facebook/8.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Arrays 计算模式_Arrays_Count_Mode - Fatal编程技术网

Arrays 计算模式

Arrays 计算模式,arrays,count,mode,Arrays,Count,Mode,我知道这是计算数据数组模式的方法 public double mode() { int maxValue=0, maxCount=0; for (int i = 0; i < a.length; i++) { int count = 0; for (int j = 0; j < a.length; j++) { if (a[j] == a[i]) ++count;

我知道这是计算数据数组模式的方法

public double mode() {
    int maxValue=0, maxCount=0;
    for (int i = 0; i < a.length; i++) {
        int count = 0;
        for (int j = 0; j < a.length; j++) {
            if (a[j] == a[i])
                ++count;
            }
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = a[i];
        }
    }
return maxValue; }
公共双模式(){
int maxValue=0,maxCount=0;
for(int i=0;i最大计数){
最大计数=计数;
最大值=a[i];
}
}
返回maxValue;}

我有一个问题,当有多个值可以是模式。因此,如果有多个值是一个模式,我想输出(返回Double.NaN;)。如何执行此操作?

添加计数相等时的条件:

if (count > maxCount) {
  maxCount = count;
  maxValue = a[i];
} else if (count == maxCount && maxValue != a[i]) {
  maxValue = Double.NaN;
}

演示(Javascript):

这不起作用。即使有一个值可以是模式,或者有多个值,它也会输出NaN。@AzariaGebo:你说得对。每个值都会计算其出现的次数,因此它与自身出现的次数相同。您必须检查它是否也是相同的值。我更新了答案。非常感谢。我花了很多时间试图弄明白这一点。你帮了很多忙。