如何计算数组列表中特定时间间隔的平均值?(How to calculate averages of particular set of intervals in an arraylist?)

编程入门 行业动态 更新时间:2024-10-11 05:28:38
如何计算数组列表中特定时间间隔的平均值?(How to calculate averages of particular set of intervals in an arraylist?)

我试图在数组列表中标识大于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; } }

更多推荐

本文发布于:2023-07-18 07:18:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1156696.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:平均值   数组   间隔   时间   列表中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!