我正在尝试制作一个小的Windows窗体应用程序,该应用程序可以让您单击一个按钮,并计算您每秒单击的次数。但是我得到了不想要的结果。
标签始终为0或1。这里的工作是使用Stopwatch类作为计时器。
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());
}
您的特权正在发挥作用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);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句