Dim timeTook As Stopwatch = Stopwatch.StartNew
'Some time-consuming tasks
timeTook.Stop()
Dim mins As Long = CLng(timeTook.Elapsed.TotalMinutes.ToString) \ 1
Dim secs As Long = CLng(timeTook.Elapsed.TotalSeconds.ToString) \ 1 - 60 * mins
Label3.Text = "Time took: " & mins & " Minutes and " & secs & " Seconds"
这可能是关于计时器或逻辑错误的事情,但它对我来说看起来很合理。我无法弄清楚什么不起作用,请帮忙。
答案 0 :(得分:1)
如果您这样做的话会更具可读性和效率:
Dim timeTook As Stopwatch = Stopwatch.StartNew
'Some time-consuming tasks
timeTook.Stop()
Label3.Text = "Time took: " & Math.Floor(timeTook.Elapsed.TotalMinutes).ToString() & " Minutes and " & timeTook.Elapsed.Seconds.ToString() & " Seconds"
或者更好:
Label3.Text = "Time took: " & timeTook.Elapsed.ToString()
Elapsed
属性已经包含了您需要的所有信息,因此您可以自行重新计算,这样做很愚蠢,而且更容易出错。
答案 1 :(得分:1)
这里的问题是CLng()函数舍入一个浮点值。因此,如果经过的时间是0.6分钟,那么你将得到分钟= 1.你的 secs 值现在将是负数。
您需要截断值,以便始终向下舍入。让我们摆脱字符串转换,这没有意义:
Dim mins = Math.Truncate(timeTook.Elapsed.TotalMinutes)
Dim secs = timeTook.Elapsed.TotalSeconds - 60 * mins
Label3.Text = String.Format("Time took: {0:N0} minutes and {1:N0} seconds", _
mins, secs)
我会将复数错误留给你解决:)
答案 2 :(得分:1)
你确定分钟是负数而不是秒吗?你的代码
Dim secs As Long = CLng(timeTook.Elapsed.TotalSeconds.ToString) \ 1 - 60 * mins
将始终返回否定因为any number / negative number is negative
。
更好的方式
Dim secs As Long = timeTook.Elapsed.TotalSeconds mod 60
答案 3 :(得分:0)
为什么不使用带有格式的.ToString?
Label3.text = timeTook.Elapsed.ToString("hh\:mm\:ss")