0

我在Percentile 计算中看到了这个函数,所以我将它复制并粘贴到编译器中,它给了我一个 OutOfRange 异常

        else
        {
            int k = (int)n;
            double d = n - k;
            return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);//EXCEPTION
        }

问题的根源可能是什么,我该如何解决?

功能:

 public double Percentile(double[] sequence, double excelPercentile)
 {
    Array.Sort(sequence);
    int N = sequence.Length;
    double n = (N - 1) * excelPercentile + 1;
    // Another method: double n = (N + 1) * excelPercentile;
    if (n == 1d) return sequence[0];
    else if (n == N) return sequence[N - 1];
    else
    {
         int k = (int)n;
         double d = n - k;
         return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);
    }
}
4

2 回答 2

2

问题是 k 是一个大于数组中项目数的数字。

于 2013-11-07T01:31:31.430 回答
1

如前所述,该函数旨在使用介于 0 和 1 之间的值。限制输入应该可以解决问题。

 public double Percentile(double[] sequence, double excelPercentile)
 {
    //if(excelPercentile > 1)
        //excelPercentile = 1;
    //else if(excelPercentile < 0)
        //excelPercentile = 0;
    //Depending on how you validate the input you can assume that it's a whole number percentage.  Then you only need to check for the number to be between 0 and 100
    if(excelPercentile > 100)
       excelPercentile = 100;
    else if(excelPercentile < 0)
       excelPercentile = 0;
    excelPercentile /= 100;
    Array.Sort(sequence);
    int N = sequence.Length;
    double n = (N - 1) * excelPercentile + 1;
    // Another method: double n = (N + 1) * excelPercentile;
    if (n == 1d) return sequence[0];
    else if (n == N) return sequence[N - 1];
    else
    {
         int k = (int)n;
         double d = n - k;
         return sequence[k - 1] + d * (sequence[k] - sequence[k - 1]);
    }
}
于 2013-11-07T03:47:01.770 回答