列表的平均值
本文关键字:平均值 列表 | 更新日期: 2023-09-27 18:08:42
我想编写的代码将在第一次单击时启动rotorSpeed
秒表,然后在第二次单击时将rotorSpeed.ElapsedMilliseconds
添加到list
。第二次点击重置秒表并再次开始计时,第三次点击将rotorSpeed.ElapsedMilliseconds
添加到list
。代码中没有错误,但当我调试它时,我在double average = list.Average();
上得到了一个错误
Stopwatch rotorSpeed = new Stopwatch();
List<double> list = new List<double>();
private void button1_Click(object sender, EventArgs e)
{
i++;
//Getting rotor speed
if (i != 2)
{
if (rotorSpeed.IsRunning)
{
rotorSpeed.Stop();
list.Add(rotorSpeed.ElapsedMilliseconds);
rotorSpeed.Start();
}
else
{
rotorSpeed.Reset();
rotorSpeed.Start();
}
}
double average = list.Average();
textBox2.Text = average.ToString();
}
这是我得到的错误:
在>System.Core.dll 中发生类型为"System.InvalidOperationException"的未处理异常
附加信息:序列不包含元素
您的list
为空,因此对其调用Average()
会引发异常。更改下线
double average = list.Average();
至
double average = list.Count > 0 ? list.Average() : 0.0;
if (list.Count > 0)
{
textBox2.Text = list.Average().ToString();
}
if (list.Count > 1)
{
double average = list.Average();
textBox2.Text = average.ToString();
rotorSpeed.Stop();
}
这很好用。谢谢