获得List的平均值

时间:2014-04-12 16:19:15

标签: c# list

我正在尝试制作这个小的Windows窗体应用程序,让您单击一个按钮,它会计算每秒点击的数量。但是我得到了不必要的结果。

标签总是0或1.我的工作是使用秒表类作为计时器。

        public List<long> clickTimes = new List<long>();

    Stopwatch stopwatch = new Stopwatch();

    long last = 0;

    private void startCalc()
    {
        stopwatch.Start();
    }

     private void stopCalc()
    {
        stopwatch.Stop();
    }

    private void resetCalc()
    {
        stopwatch.Reset();
    }

    private long time()
    {
        return stopwatch.ElapsedMilliseconds;
    }

    private bool isOn()
    {
        return stopwatch.IsRunning;
    }

    private long frequencyFromInterval(long ms)
    {
        return 1000 / ms;
    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (isOn() == false)
        {
            startCalc();
        }
        last = time() - last;
        clickTimes.Add(last);
    }

    private void button2_Click(object sender, EventArgs e)
    {
        long avg = 0;

        for (int i = 0; i < clickTimes.Count; i++)
        {
            avg = avg + clickTimes[i];
        }
        avg = avg / clickTimes.Count;
        avg = frequencyFromInterval(avg);
        label1.Text = "Avg. CpS: " + avg.ToString());
    }

3 个答案:

答案 0 :(得分:1)

从快速浏览代码开始,我认为您的问题是由于您使用long类型的值,这些值除以后,只能返回数字的整数部分。尝试使用floatdouble类型。

答案 1 :(得分:1)

您的peroblem处于divide操作中。它会自动将值舍入为long,因为所有操作数都是long类型,结果是long

private void button2_Click(object sender, EventArgs e)
{
    double sum = 0;
    for (int i = 0; i < clickTimes.Count; i++)
    {
        sum += clickTimes[i];
    }
    double avg = sum / clickTimes.Count;
    double frequency = FrequencyFromInterval(avg);
    label1.Text = "Avg. CpS: " + frequency.ToString());
}

private double FrequencyFromInterval(double ms)
{
    return 1000 / ms;
}

button1_Click方法中也存在一个小错误。查找last时使用不同的值并添加到clickTimes列表。您应该通过time方法缓存您获得的值。

long time = time();
last = time  - last;
clickTimes.Add(time);

答案 2 :(得分:0)

如何在列表中使用Average功能,如此

double average = clickTimes.Average();