争论超出范围异常抛出

时间:2013-11-07 01:30:21

标签: c#

我在Percentile calculation上看到了这个函数,所以我复制了它并将其粘贴到编译器中,它给了我一个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]);
    }
}

2 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分: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]);
    }
}