因此,我正在编写一种方法来计算排序数组的模式。但是,当我打印出模式值时,它总是显示为0.00,而我试图对其进行修复,但无法解决。
这是此方法的代码:
(numRead是传递的数组,num是实际具有值的数组长度)

public static void modeCalc(double[] numRead, int num)
    {
        double maxValue = numRead[0];
        int maxCount = 0;
        for (int i = 0; i < numRead.length; i++)
        {
            int count = 0;
            for (int j = 0; j < numRead.length; j++)
            {
                if (numRead[j] == numRead[i])
                    count++;
            }
            if (count > maxCount)
            {
                maxCount = count;
                maxValue = numRead[i];
            }
        }
        return maxValue;
    }


任何帮助深表感谢!

最佳答案

这应该工作。您需要返回一个双精度数,并且需要使用num。

class ModeArray
{
    public static void main(String[] args) {
        double[] numRead = { 1, 2, 3, 3, 4, 4, 4, 5, 0, 0, 0, 0, 0 };
        System.out.println(modeCalc(numRead, 8));
    }

    public static double modeCalc(double[] numRead, int num) {
        double maxValue = numRead[0];
        int maxCount = 0;
        for (int i = 0; i < num; i++) {
            int count = 0;
            for (int j = 0; j < num; j++) {
                if (numRead[j] == numRead[i]){
                    count++;
                }
            }
            if (count > maxCount) {
                maxCount = count;
                maxValue = numRead[i];
            }
        }
        return maxValue;
    }
}


如果您知道数组已排序,则应使用此信息。

public static double modeCalc(double[] numRead, int num) {
    double maxValue = numRead[0];
    double lastValue = maxValue;
    int count = 1;
    int maxCount = 1;
    for (int i = 1; i < num; i++) {
        if (numRead[i] == lastValue) {
            count++;
        } else {
            count = 1;
            lastValue = numRead[i];
        }
        if (count > maxCount) {
            maxCount = count;
            maxValue = lastValue;
        }
    }
    return maxValue;
}


PS:请不要在不使用大括号的情况下使用if语句。它使添加错误变得更加容易,而更加难以发现它们。

07-26 07:10
查看更多