您需要将CalcolaRPM()
方法外围绕保持一个秒表,如果你想一次情况插图中调用它。
最简单的事情做的是将其添加为在类的私人领域。
另一个问题是,当不是“1”时,您需要返回最后一个已知RPM - 我们可以通过将最后一个已知RPM保留在专用字段中来解决该问题。
而另一个问题是,RPM计算的第一次,也不能因为没有时间前述将其与比较准确。我们将通过返回-1
解决此问题,直到我们有正确的时间进行报告。
而接下来,您要计算经过RPM为整数计算。现在想象一下,如果事情稍微有点过了,那么经过的时间总是999毫秒。只有一毫秒,但你的RPM = 999/1000的计算结果为零。
您有几种选择,但最有可能的是:
我去四舍五入。 RPM的计算是不正确的,所以我纠正在同一时间:
lastRPM = (int) Math.Round(60000.0/((int) stopWatch.ElapsedMilliseconds));
把那干脆,这里有一个编译测试程序(控制台应用程序):
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading;
namespace Demo
{
class Rpm
{
private Stopwatch stopWatch = new Stopwatch();
private int lastRPM = -1;
// RPM will be -1 until we have received two "1"s
public int CalcolaRPM(string giriRicevuti)
{
if (giriRicevuti == "1")
{
if (stopWatch.IsRunning)
lastRPM = (int) Math.Round(60000.0/((int) stopWatch.ElapsedMilliseconds));
stopWatch.Restart();
}
return lastRPM;
}
}
class Program
{
void run()
{
test(900);
test(1000);
test(1100);
test(500);
test(200);
}
void test(int interval)
{
Rpm rpm = new Rpm();
for (int i = 0; i < 10; ++i)
{
Thread.Sleep(interval);
rpm.CalcolaRPM("0");
rpm.CalcolaRPM("1").Print();
rpm.CalcolaRPM("2");
}
}
static void Main()
{
new Program().run();
}
}
static class DemoUtil
{
public static void Print(this object self)
{
Console.WriteLine(self);
}
public static void Print(this string self)
{
Console.WriteLine(self);
}
public static void Print<T>(this IEnumerable<T> self)
{
foreach (var item in self) Console.WriteLine(item);
}
}
}
你什么时候调用这个方法? – bpoiss
您的方法会启动秒表,然后立即测量秒表的运行时间 - 这显然不是很长时间,因为您刚开始秒表。 – dtb
@dtb,当我得到下一个“1”时应该停止。这正是我想要实现的。我已经提出了一个停止的条件。但显然不工作。 – FeliceM