<list> C#的平均值

时间:2016-09-21 07:44:51

标签: c# list button stopwatch

我需要将<List>的平均值写入textBox1的代码。点击button1 2次textBox1应该会给出rotorSpeed的平均值ElapsedMilliseconds。

    Stopwatch rotorSpeed = new Stopwatch();
    List<double> list = new List<double>();
    double av;

    private void button1_Click(object sender, EventArgs e)
    {
        int i = 0;
        i++;
        do
        {
            if (rotorSpeed.IsRunning)
            {
                rotorSpeed.Stop();
                list.Add(rotorSpeed.ElapsedMilliseconds);
                continue;
            }
            else
            {
                rotorSpeed.Reset();
                rotorSpeed.Start();
            }
        } while (i == 2);

        av = list.Average();
        textBox1.Text = av.ToString();
    }
}

1 个答案:

答案 0 :(得分:-1)

你应该把i的初始化放在事件之外

Stopwatch rotorSpeed = new Stopwatch();
List<double> list = new List<double>();
double av;
int i = 0;

private void button1_Click(object sender, EventArgs e)
{
    i++;
    if (i == 2)
    {
        if (rotorSpeed.IsRunning)
        {
            rotorSpeed.Stop();
            list.Add(rotorSpeed.ElapsedMilliseconds);
            continue;
        }
        else
        {
            rotorSpeed.Reset();
            rotorSpeed.Start();
        }
        i=0;
    } 

    av = list.Average();
    textBox1.Text = av.ToString();
}

}