当前位置: 动力学知识库 > 问答 > 编程问答 >

c# - How to calculate averages of particular set of intervals in an arraylist?

问题描述:

I'm trying to identify values that are greater than 200 in an array-list and calculate averages of these values for each interval. My array-list is,

List<int> numlist = new List<int>();

and it contains values,

numlist.Add(50);

numlist.Add(67);

numlist.Add(98);

numlist.Add(150);

numlist.Add(230);

numlist.Add(250);

numlist.Add(260);

numlist.Add(87);

numlist.Add(98);

numlist.Add(201);

numlist.Add(254);

numlist.Add(164);

As you can see, the first set of consecutive values that are greater than 200 is 230,250 and 260. The second set of values are 201 and 254.

I want to loop through the array-list and identify these two sets separately and then calculate their averages.

average 1: (230 + 250 + 260)/3

average 2: (201 + 254)/2

How can I achieve this?

网友答案:

This code should achieve what you want, it will produce another list containing all the averaged values of consecutive numList entries over 200 (but not equal to 200!);

        var sum = 0;
        var count = 0;
        var averages = new List<double>();
        foreach (var t in numlist)
        {
            if (t > 200)
            {
                sum += t;
                count += 1;
            }
            else
            {
                if (sum == 0) continue;
                var average = (double) sum/count;
                averages.Add(average);
                sum = 0;
                count = 0;
            }
        }
分享给朋友:
您可能感兴趣的文章:
随机阅读: