问题描述
在每帧调用的方法中,我只需要计算最近 10 个浮点值的平均值,并且浮点值不断变化。
1- 我能正确获得 10 个最近的浮点数的平均值吗?
谢谢!
List<float> floatVals= new List<float> { };
Update(){
floatVals.Add(myChangingFloatVal);
if(floatVals.Count>=10){
floatVals.RemoveRange(0,1);
_averageFloat= floatVals.Average();
}
解决方法
我希望在您的平均方法之外有一个列表。此外,我没有看到您的示例中的 changesFloatValue 变化。显示的 for 循环会将相同的值推入列表 10 次,平均值与该值相同。考虑改成这样。
// Max number of values to average
//
private int maxAverageValues = 10;
// Running list of values to average
//
private List<float> valuesToAverage = new List<float>();
private float AddValueGetAverage(float newValue)
{
// New values are added to the end of the list
//
valuesToAverage.Add(newValue);
// Check if we exceeded the max amount of values we want to average
//
if (valuesToAverage.Count > maxAverageValues)
{
// Max exceeded,remove the oldest value
//
valuesToAverage.RemoveAt(0);
}
// Return the average
//
return valuesToAverage.Sum() / valuesToAverage.Count;
}
编辑
根据 Amys 的建议,这里是使用 Queue 而不是 List 的相同代码。
根据微软的文档: 存储在队列中的对象在一端插入并从另一端移除。当您需要临时存储信息时,队列和堆栈很有用;也就是说,当您可能想要在检索其值后丢弃某个元素时。如果您需要按照信息存储在集合中的相同顺序访问信息,请使用队列。
private int maxValuesForFloatingAverage = 10;
private Queue<float> floatingAverageValues = new Queue<float>();
private float changingFloat = 0f;
private float changingFloatAvg = 0f;
void Update()
{
// update the changing float value here...
// Enqueue the new value
//
floatingAverageValues.Enqueue(changingFloat);
// Check if we exceeded the amount of values we want to average
//
if (floatingAverageValues.Count > maxValuesForFloatingAverage)
{
// Max exceeded,dequeue the oldest item
//
floatingAverageValues.Dequeue();
}
// Take the average
//
changingFloatAvg = floatingAverageValues.Sum() / floatingAverageValues.Count;
}