+-
c# – Percentile算法
我正在写一个找到百分位数的程序.根据eHow:

Start to calculate the percentile of your test score (as an example we’ll stick with your score of 87). The formula to use is L/N(100) = P where L is the number of tests with scores less than 87, N is the total number of test scores (here 150) and P is the percentile. Count up the total number of test scores that are less than 87. We’ll assume the number is 113. This gives us L = 113 and N = 150.

所以,根据指示,我写道:

        string[] n = Interaction.InputBox("Enter the data set. The numbers do not have to  be sorted.").Split(',');
        List<Single> x = new List<Single> { };
        foreach (string i in n)
        {
            x.Add(Single.Parse(i));
        }
        x.Sort();
        List<double> lowerThan = new List<double> { };
        Single score = Single.Parse(Interaction.InputBox("Enter the number."));
        uint length = (uint)x.Count;
        foreach (Single index in x)
        {
            if (index > score)
            {
                lowerThan.Add(index);
            }
        }
        uint lowerThanCount = (uint)lowerThan.Count();

        double percentile = lowerThanCount / length * 100;
        MessageBox.Show("" + percentile);

然而,该程序总是返回0作为百分位数!我犯了什么错误?

最佳答案
这实际上是一个舍入问题,lowerThanCount / length都是单位因此不支持小数位,因此任何自然百分比计算(例如0.2 / 0.5)都会导致0.

例如,如果我们假设lowerThanCount = 10且length = 20,则总和看起来像

double result = (10 / 20) * 100

因此导致

(10 / 20) = 0.5 * 100

由于0.5不能表示为整数,因此浮点被截断,使得0为零,因此最终的计算最终会变为

0 * 100 = 0;

您可以通过强制计算使用浮点类型来解决此问题,例如

double percentile = (double)lowerThanCount / length * 100 

就可读性而言,在给定lowerThanCount& of计算的计算中使用强制转换可能更有意义.长度自然不会是浮点数.

此外,使用LINQ可以简化您的代码

string[] n = Interaction.InputBox("Enter the data set. The numbers do not have to  be sorted.")
                        .Split(',');
IList<Single> x = n.Select(n => Single.Parse(n))
                   .OrderBy(x => x);
Single score = Single.Parse(Interaction.InputBox("Enter the number."));
IList<Single> lowerThan = x.Where(s => s < score);
Single percentile = (Single)lowerThan.Count / x.Count;
MessageBox.Show(percentile.ToString("%"));
点击查看更多相关文章

转载注明原文:c# – Percentile算法 - 乐贴网