我试图在数组列表中标识大于200的值,并计算每个间隔的这些值的平均值。 我的数组列表是,
List<int> numlist = new List<int>();它包含值,
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);正如你所看到的,大于200的第一组连续值是230,250和260.第二组值是201和254。
我想遍历数组列表并分别标识这两组,然后计算它们的平均值。
平均1:(230 + 250 + 260)/ 3
平均2:(201 + 254)/ 2
我怎样才能做到这一点?
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?
最满意答案
这个代码应该实现你想要的,它会产生另一个列表,其中包含200个连续numList条目的所有平均值(但不等于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; } }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; } }更多推荐
发布评论